Search code examples
smlsmlnj

SML pair tuples conversion


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?


Solution

  • 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