Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No instance for Foldable arising from length inside lambda

first question here and completely a noob on haskell, so please be kind with me :)

I was playing with the question number 6 of this haskell exercises

and in the end came to the solution (or something similar I hope) with this code

combinations gr lis = filter clean $ sequence $ replicate gr lis
where
    clean string
        | total > gr = False
        | otherwise = True
        where total = sum [ rpt c string | c <- string]
    rpt chr list = length $ filter (== chr) list

the part that i like to be highlighted is the function 'rpt' which counts the number of times a character is repeated in a string, for example: "aaba" -> [3313] (the 3 comes from the letter a, which repeates 3 times) "aaccva" -> [332213]

later on I tried to make the function with a lambda and a map resulting in this:

rpt chr list = map (\chr -> length $ filter (== chr)) list

and at first ghci told me to use FlexibleContext to allow this, but if I do then it yields:

<interactive>:7:1:
No instance for (Foldable ((->) [Char]))
  arising from a use of ‘rpt’
In the expression: rpt 'a' string
In an equation for ‘it’: it = rpt 'a' string

and here I'am stuck, I have not been able to understand what's happening... what is needed to fix this function?

like image 767
iPizarro12 Avatar asked Nov 16 '16 20:11

iPizarro12


1 Answers

You likely are intending to filter over list, so to make your code work, you need to also add list as an argument of filter:

rpt chr list = map (\chr -> length $ filter (== chr) list) list

For beginners, I recommend ignoring GHCi's suggestion of FlexibleContexts. It often ends up producing error messages like the one you had (or other confusing ones like No instance for (Num (Int -> Bool))).

like image 76
Alec Avatar answered Oct 04 '22 17:10

Alec