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?
clean string = total <= gr where ...
since using guards or if-then-else to return true/false looks more complex than it needs to be 2) your algorithm for combinations looks correct but suboptimal: you generate many candidates, and you need to filter them out later. Consider this: you can pick k elements fromx:xs
by either skippingx
(and taking all k elements fromxs
) or choosingx
(and then taking only k-1 elements fromxs
). – Bagwell