I'm trying to write a Haskell function that uses folds and will take a string and return its "word value" as an int. This is the function:
import Data.Char
wordValue :: String -> Int
wordValue (x:xs) = foldr (\(ord(toLower x) - (ord 'a') 1)) 0 xs
Basically, i'm trying to convert each character into a int value and use the 'foldr' function to accumulate the value. But, I'm getting the following error, which I don't understand:
Parse error in pattern: ord (toLower x) - (ord 'a') 1
CodePudding user response:
The foldr
function also take two parameters: the item of the list, and the result of the foldr
of the tail. You thus should implement this as:
wordValue :: String -> Int
wordValue xs = foldr (\x ys -> ord (toLower x) - ord 'a' ys 1) 0 xs
where x
is the character of the list, and ys
is the result of folding the rest of the list (so the wordValue
of the remaining elements).
But here it is simpler to just work with a mapping and summing these up, so:
wordValue :: String -> Int
wordValue = sum . map (\x -> ord (toLower x) - ord 'a' 1)