Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip and unzip lists in Standard ML

Tags:

sml

smlnj

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]]
like image 705
jetpackman Avatar asked Dec 06 '25 21:12

jetpackman


1 Answers

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.

like image 198
Matt Avatar answered Dec 10 '25 11:12

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!