0
votes

I've been trying to solve this pair tuples problem where the input is a list of tuples and the output is a tuple of lists where the first element of each tuple is grouped together and similarly with the second (i.e. [(1,2),(3,4),(5,6)] --> ([1,3,5],[2,4,6])).

I've thought of this code but it gives me an error:

 fun convert L = foldl (fn ((x,y),(u,v)) => ((u@x),(v@y)) ([],[]) L;

Any suggestions for a fix?

2

2 Answers

3
votes

Concatenation (@) takes two lists, but x and y are values, so you need to wrap them with [] to make a single-element list:

fun convert l=foldl (fn((x,y),(u,v))=>(u@[x],v@[y])) (nil,nil) l

You can use cons instead of concatenation, though the lists inside the returned tuple are reversed:

fun convert l=foldl (fn((x,y),(u,v))=>(x::u,y::v)) (nil,nil) l
1
votes

@ concatenates lists (and x and y are not lists).

Try (u@[x],v@[y]).

Note, however, that appending is a linear-time operation, while prepending (i.e. x::u) is constant. As Alex pointed out, this will build your lists in reverse, but you can resolve this by processing your input in reverse as well - i.e., by using foldr instead of foldl.