How to create a function to zip and unzip two lists as tupled lists in Standard ML?
Example:
unzip [[1,4],[2,5],[3,6]] -> [1,2,3] [4,5,6]
zip [1,2,3] [0,2,4] -> [[1,0],[2,2],[3,4]]
It is usually not a good idea to use head
and tail
, but instead to use pattern matching. You can encode unzip a bit more elegantly as follows:
fun unzip l =
case l
of nil => (nil, nil)
| (a,b)::tl =>
let val (l1, l2) = unzip tl
in (a::l1, b::l2) end
Also as one of the commenters above mentioned, zip and unzip typically work on pairs of lists, and lists of pairs respectively.