Working on a Haskell problem, fairly new to the language. I am trying to count the occurence of tuple values that are present in the list of tuples.
My tuples look like this: [(5, [7,2]), (2,[5,7,1,6])]
So far, using foldr
, I have done this:
testFunc = foldr (\x-> const succ) 0
However, this only retrieves the count of the left side of the tuple. I am a little confused, how to solve this?
-- Expected output: 6
-- Current output: 2
CodePudding user response:
The type of foldr
is:
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
This means that the function it's talking should take the current value and the accumulator and will return a value of the same type as the accumulator. It then takes an initial value for the accumulator, and finally the Foldable
thing to iterate over.
The accumulator is clearly the count, and for an empty list, it'll be zero, so there's our initial accumulator value.
We then just have to add the length of the list to that accumulator each time through. We can pattern match this data out. We'll use _
for the first item in each tuple, because we just don't care about that value.
Prelude> testData = [(5, [7,2]), (2,[5,7,1,6])]
Prelude> foldr (\(_, lst) count -> count length lst) 0 testData
6
Prelude>