I am new in haskell and I have a problem (aka homework).
So, I have a list with a tuple – a string and an integer:
xxs :: [([Char], Integer)]
I need to know how many of the strings in xxs start with a given character.
Let me exemplify:
foo 'A' [("Abc",12),("Axx",34),("Zab",56)]
Output: 2
foo 'B' [("Abc",12),("Bxx",34),("Zab",56)]
Output: 1
My best attempt so far:
foo c xxs = length (foldl (\acc (x:xs) -> if x == c then c else x) [] xxs)
But, of course, there’s something VERY wrong inside the lambda expression.
Any suggestion?
Thanks.
There are a few problems with your attempt:
You plan to use
foldlto construct a shorter list and then to take its length. While it is possible,filterfunction is much better suited for that task as @landei suggestsfoldlcan be used to accumulate the length without constructing a shorter list. See the answer of @WuXingbo – his answer is incorrect, but once you realize thatlengthis not needed at all with his approach, it should be easy for you to come with correct solution.Somewhat contradictory to common sense, in a lazy language
foldris faster and uses less memory thanfoldl. You should ask your teacher why.