3

Given a list of tuples,

[(1,2),(3,4),(5,6)]

I need to unzip it to look like this

 [[1,3,5],[2,4,6]]

unzip needs to be of type ('a * 'a) list -> 'a list list.

So far, I have this as my unzip function but my input is incorrect, and I am not sure how to access pass through ('a * 'a).

val rec last =
        fn (h::nil) => h
           |(h::list) => last (list)
           | (nil) => raise Empty;

fun unzip [] = []
    | unzip L = [(map hd L), (map last L)]; 

this returns 'a list list -> 'a list list

  • Since your `L` is supposed to be a list of *tuples*, `map hd L`wouldn't make sense since tuples don't have heads. It is also problematic that your `unzip` is nonrecursive. I don't see how `map` is really relevant to `unzip`. A straightforward recursive definition based on pattern matching should work. – John Coleman Feb 22 '18 at 02:05

2 Answers2

4

You were given a list of tuples

[(1,2),(3,4),(5,6)]

And we want to create a function to re-organize them into

[[1,3,5],[2,4,6]]

We know the output should look something like:

[ [tuple heads], [tuple tails] ]

And we know map gives us an output of list, which is the datatype we are looking for.

Thus,

fun unzip L = [ (map f1 L), (map f2 L) ]

I recognize this as a homework problem, so I will leave it there for you to think about the appropriate function for map. Think about how tuple behave and how do you manipulate data inside a tuple. Remember that f1 should be different from f2 as the two manipulate different things.

Go Cougs!

  • Go Cougs!! Thanks for the insight! – Jhenna Foronda Feb 22 '18 at 06:37
  • 1
    But a list like `[ (map f L), (map f L) ]` would be a 2-element list whose first and second components are identical, hence couldn't look like `[[1,3,5],[2,4,6]]`. You would need to map two *different* functions over `L` (if you wanted to use map). – John Coleman Feb 22 '18 at 10:21
  • Yes, the function for the first element should be different from the second. I've edited the code to resemble the idea. – Yuka Langbuana Feb 23 '18 at 19:22
1

You can also unzip using foldr in the following way:

val unzip = foldr (fn ((x,y), (xs, ys)) = (x::xs, y::ys)) ([], [])
sshine
  • 15,635
  • 1
  • 41
  • 66