Koin Arab
Koin Arab

Reputation: 1107

Error in types in haskell

I get this error:

Type error in application
*** Expression     : length (filter (flip (==) x))
*** Term           : filter (flip (==) x)
*** Type           : [b] -> [b]
*** Does not match : [a]

This is my code:

numocc::(Eq a) => a -> [[a]] -> [Int]
numocc = map.((length.).(f))

f:: (Eq a) => a -> [a] -> a
f = filter.(flip (==))

I cannot understand the types. Can anybody help me?

Upvotes: 1

Views: 69

Answers (2)

If I put the definition of f in ghci, I get:

Expected type: (a -> Bool) -> [a] -> a
  Actual type: (a -> Bool) -> [a] -> [a]
In the first argument of `(.)', namely `filter'
In the expression: filter . (flip (==))

In other words, what results here is a list of type a, when a single instance of type a is expected. If you're applying a predicate to a list, and the result should be a single instance, then you'll probably want to make a fold of some kind.

Changing the type of f to

f:: (Eq a) => a -> [a] -> [a]

makes this code compile.

Upvotes: 3

Shoe
Shoe

Reputation: 76240

You are trying way too hard to be point free, just use:

f :: (Eq a) => a -> [a] -> [a]
f x = filter (== x)

and then:

numocc :: (Eq a) => a -> [[a]] -> [Int]
numocc x = map (length . f x)

Live demo

Upvotes: 4

Related Questions