Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Thomas Heywood Avatar asked Aug 28 '10 22:08

Thomas Heywood


People also ask

How pattern matching is used in scripting language?

The implementation of pattern matching into JavaScript greatly aids in the processing of data for the Internet. JavaScript uses the RegExp (short for Regular Expression) object to handle pattern matching. This object holds the pattern definition, as well as provides methods for performing matching.

What is pattern matching rules?

Matches any number (or none) of the single character that immediately precedes it. For example, bugs* will match bugs (one s ) or bug (no s 's). The character preceding the * can be one that is specified by a regular expression. For example, since . (dot) means any character, .

How does pattern matching work in OCaml?

Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.


1 Answers

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)
like image 148
sepp2k Avatar answered Oct 13 '22 03:10

sepp2k