Home > Back-end >  Haskell list of pairs to pairs of lists
Haskell list of pairs to pairs of lists

Time:10-18

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:

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

CodePudding user response:

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.

  • Related