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.
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.
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, .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With