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 list of pairs to pairs of lists

I have seen here, that there are several approaches to solve it, but I am struggling to solve it with recursion.

Example: [("a",1), ("b",2)] to (["a","b"] ,[1,2])

I have so far:

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

listOfPairs :: [ ( String , Int ) ] -> ( [ String ] , [ Int ] )
listOfPairs((a,b): xs) = ([a], [b]) -- and here I don't know how to call the function again with the rest xs

I have tried listOfPairs((a,b): xs) = ([a], [b]) + listOfPairs xs but obviously it doesn’t work.

Maybe someone has an idea.
Thank you

>Solution :

This is the idea behind unzipping:

listOfPairs :: [(a, b)] -> ([a], [b])
listOfPairs = unzip

As for a recursive approach, you should make a recursive call and then append the elements to the the two items of the 2-tuple, so:

listOfPairs :: [(a, b)] -> ([a], [b])
listOfPairs [] = …
listOfPairs ((a, b):xs) = (a : …, b : …)
    where ~(as, bs) = listOfPairs …

Where I leave filling in the parts as an exercise.

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