Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding via argument name and pattern match in ocaml

In OCaml, how can I both :

  • pattern match on an argument
  • and also bind the unmatched argument to a name ?

in haskell it is like

f arg@{..} = some code using both arg and its fields
like image 795
nicolas Avatar asked Oct 29 '18 09:10

nicolas


People also ask

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.

What does H :: t mean in OCaml?

What does H :: t mean in OCaml? The pattern h :: t matches any non-empty list, calls the head of the list h (one element, the first one), and the tail of the list t (zero or more elements after the first one).

What does :: mean in OCaml?

If you have two variables called x and xs' then x :: xs' creates a new list with x prepended onto the front of xs' .

What is () in OCaml?

This is a way to indicate there is no value for an argument. It's necessary to do this in ML because all functions are unary. You can't have a function with zero arguments, so instead you pass an argument containing no information, which is () .


1 Answers

Use as. E.g.:

let f ((a, b) as original) =
  if a > b then
    (b, a)
  else
    original

or:

let g = function
| [] -> []
| (x :: _) as l -> x :: l
like image 192
glennsl Avatar answered Nov 13 '22 05:11

glennsl