Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell – counting with foldr

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading