Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse error when trying to run haskell function?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading