Home > Mobile >  Erroneous use of simple Haskell function
Erroneous use of simple Haskell function

Time:02-24

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:

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.

CodePudding user response:

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.

  • Related