Thomas Heywood
Thomas Heywood

Reputation: 923

how to pattern match on an arbitrary number of arguments?

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.

Upvotes: 12

Views: 11011

Answers (1)

sepp2k
sepp2k

Reputation: 370102

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)

Upvotes: 18

Related Questions