No instance for Foldable arising from length inside lambda

the first question is here and completely noob on haskell, so please be kind to me :)

I played with question number 6 this haskell exercise

and finally came up with a solution (or something similar to me) 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 highlight is the 'rpt' function, which counts the number of times a character repeats in a string, for example: "aaba" → [3313] (3 comes from the letter a, which repeats 3 times) "aaccva" → [332213]

I later tried to make a function with a lambda and a map, resulting in the following:

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

and first ghci told me to use FlexibleContext to allow this, but if I do, it will give:

 <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 could not understand what was happening ... what is needed to fix this function?

+5
source share
1 answer

You probably intend to filter more than list , so oo will make your code work, you also need to add list as a filter argument:

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

As a newbie, I would ignore the GHCi FlexibleContexts suggestion. This often does not lead to error messages like the ones you had (or other confusing things like No instance for (Num (Int -> Bool)) ).

+5
source

Source: https://habr.com/ru/post/1259860/


All Articles