Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a list of tuples into two lists in haskell using the map function?

Tags:

haskell

map

unzip

This is for homework due yesterday but I do not want the answer just a point to the right direction please;)

I am trying to implement the unzip function using map and lambda with haskell.

:t unzip
[(a,b)] -> ([a],[b]) 

and so I am thinking that the lambda would look like \(a,b)->([a],[b]) and that sort of works except I am getting from my input of [(4,5),(7,5),(9,7)] => [([4],[5]),([7],[5]),([9],[7])] but I would have liked to have seen [4,7,9],[5,5,7]. So what am I doing wrong here?

Thanks in advance for pointing me in the right direction

like image 939
baron aron Avatar asked Dec 20 '22 21:12

baron aron


2 Answers

Well, map :: (a -> b) -> ([a] -> [b]) returns a list, right? And you want your function to return two lists, so... you'll need to use map twice. Here's a skeleton for you to fill in:

unzip xs = (map {- ??? -} xs, map {- ??? -} xs)

Unfortunately, insisting on using map is inefficient, because it means you must make two passes over the list. You can do a bit better, but it's tricky! Give it a shot, then see how well you did by comparing it with GHC's implementation.

like image 76
Daniel Wagner Avatar answered May 02 '23 08:05

Daniel Wagner


you can not implement unzip in a single map

\(a,b)->([a],[b]) :: (a,b) -> ([a],[b])

so

map \(a,b)->([a],[b]) :: [(a,b)] -> [([a],[b])]

instead you need two maps

unzip ls = (map ???,map ???)

fill in the blanks

like image 34
Philip JF Avatar answered May 02 '23 10:05

Philip JF