how to pattern match on an arbitrary number of arguments?

10,235

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)
Share:
10,235
Thomas Heywood
Author by

Thomas Heywood

Updated on June 05, 2022

Comments

  • Thomas Heywood
    Thomas Heywood almost 2 years

    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.