Error "unification would give infinite type" in haskell

1

I'm trying to define a function that given an element and a list to count the number of times that element appears on that list, then I have:

cuantasVecesAparece :: Eq a => a -> [a] -> Int
cuantasVecesAparece p [] = 0
cuantasVecesAparece p [x:xs] =  if p == x
                                then 1 + cuantasVecesAparece xs 
                                else cuantasVecesAparece xs

But I get the following error:

ERROR file:.\ff1.hs:272 - Type error in application
*** Expression     : p == x
*** Term           : p
*** Type           : [a]
*** Does not match : a
*** Because        : unification would give infinite type

I do not understand why I'm taking p as a list.

    
asked by Ramiro 05.04.2017 в 02:52
source

2 answers

2

The problem is the pattern matching you are using. You are saying that you receive a list [x:xs] of a single element, which is another list with head x and queue xs . Use (x:xs) instead of [x:xs] .

Also, you are missing the first argument in the recursive call:

cuantasVecesAparece :: Eq a => a -> [a] -> Int
cuantasVecesAparece _ [] = 0
cuantasVecesAparece p (x:xs) = if p == x
                               then 1 + cuantasVecesAparece p xs 
                               else cuantasVecesAparece p xs
    
answered by 05.04.2017 в 11:53
0

The pattern you are using infers that if [x:xs] is of type [a] , then x:xs , which is a list, is of type a , the same type as p that, therefore It is also a list.

The appropriate pattern would be (x:xs) so that both x as p have the same type. My advice is not to use if 's in favor of guards in the definition of the function:

cuantasVecesAparece :: Eq a => a -> [a] -> Int
cuantasVecesAparece _ [] = 0
cuantasVecesAparece p (x:xs) | p == x    = 1 + cuantasVecesAparece p xs
                             | otherwise = cuantasVecesAparece p xs

Although there would be a more effective way:

cuantasVecesAparece :: Eq a => a -> [a] -> Int
cuantasVecesAparece p = length . filter (==p)
    
answered by 09.04.2017 в 04:54