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

Erroneous use of simple Haskell function

I’m learning Haskell and there’s a lot of type-checking that seems completely nonsensical to me. I have written a simple function to count the number of occurrences of a given element in a given list, as such:

-- Count the number of occurrences of an element in a list.
countOcc :: (Eq a) => [a] -> a -> Int
countOcc xs x = length $ filter (== x) xs

Now, using this explicitly with calls such as:

countOcc "str" 's'

This executes fine, and returns correctly. However, this causes an error:

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

countOcc "str" "str"!!0

I haven’t the foggiest why this should cause an error. "str"!!0 gives ‘s’, a Char, which is exactly the same type passed in the second parameter of the first call.

I’m sure there are some nuances to Haskell’s type system that I’m overlooking, or haven’t broached yet. Ideally, I’d like to know why this is erroneous and furthermore, I’d like to know, according to Haskell’s ideology, why it should be erroneous.

>Solution :

The following works fine:

countOcc :: (Eq a) => [a] -> a -> Int
countOcc xs x = length $ filter (== x) xs

main = print $ countOcc "str" ("str"!!0) -- 1

As far as I know, function applictaion has the highest precedence; although !! has precedence level of 9, it is still lower than function application.

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