views:

133

answers:

1

Hi all,

is there an OCaml equivalent to Haskell's pattern matching on an arbitrary number of arguments? For example, can I have something resembling:

merge [] lst = lst
merge lst [] = lst
merge l1 @ (n : ns) l2 @ (m : ms) = 
  if n < m then n : merge ns l2 else m : merge l1 ms

(The example's lifted from Developing Applications with Objective Caml :)

Thanks.

+8  A: 

You can't match multiple arguments as such, but you can match tuples, so you can do:

let rec merge l1 l2 = match l1, l2 with
| [], lst
| lst, [] -> lst
| (n::ns), (m::ms) -> if n < m then n :: merge ns l2 else m :: merge l1 ms

If you're ok with the function taking its arguments as a tuple you can also use function like this:

let rec merge = function
| [], lst
| lst, [] -> lst
| (n::ns as l1), (m::ms as l2) -> if n < m then n :: merge (ns, l2) else m :: merge (l1, ms)
sepp2k