Mail and unpacked lists in standard ML

How do I create a function to zip and unzip two lists as 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]]

      

+3


source to share


3 answers


It is generally not recommended to use head

and tail

, but use pattern matching instead. You can code unzip somewhat more elegantly like this:

fun unzip l = 
  case l
    of nil => (nil, nil)
     | (a,b)::tl => 
        let val (l1, l2) = unzip tl
        in (a::l1, b::l2) end

      



Like one of the commenters above, zip and unzip usually work on pairs of lists and lists of pairs, respectively.

+1


source


I figured out what I was doing wrong. Here's the code:

fun zip nil nil = nil
  | zip nil l = l
  | zip l nil = l
  | zip (h::t) (k::l) = [h,k]::(zip t l)
fun mapcan(f,nil) = nil | mapcan(f,h::t) = (f h)@(mapcan(f,t))
fun unzip (l) = if (l = nil) then nil else [(map head l),(mapcan tail l)]

      



Unpacking is a little tricky. We need display functions that select the first and second items of a two-item list from a zipped list. Since the problem is somewhat unproven in the example, we put the rest of the longer list in the first list. To avoid the problem of empty tails for a shorter list, we use the mapcan function, which adds lists of tails.

+2


source


There is absolutely no need for operator-entered lexical coverage let

. By defining projection functions, a much more concise and elegant representation can be obtained:

fun fst p =
   case p of 
      (x,_) => x

fun snd p =
   case p of
      (_,y) => y

fun unzip lp =
   case lp of 
      [] => ([], [])
    | (x,y) :: lp' => (x :: (fst (unzip lp')), y :: (snd (unzip lp')))

      

There is a good reason why this works, namely that the Type-Inference from the SML compiler is powerful enough to infer types of terms from case statements and cons statements. Computational functions are deduced prior to this, and CSP for Type Constraints is resolvable. IMO, this is much more elegant than the solutions presented earlier with the instructions let

.

Compiler

0


source







All Articles