Star
You must be signed in to star a gist
Labeled and optional arguments in OCaml, by example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open Printf | |
(* Labeled arguments, the easy way *) | |
let _ = | |
(* Declare a function with labeled arguments like this: *) | |
let f ~x ~y = x + y in | |
(* Type: f : x:int -> y:int -> int *) | |
(* Call it like this: *) | |
printf "%d\n" (f ~x:5 ~y:6); | |
(* You can also "pun" the argument names *) | |
let x = 5 in | |
let y = 6 in | |
printf "%d\n" (f ~x ~y) | |
(* Labeled arguments using labels that are different than the argument | |
ids *) | |
let _ = | |
let f ~x:foo ~y:bar = foo + bar in | |
(* Type is still f : x:int -> y:int -> int *) | |
printf "%d\n" (f ~x:5 ~y:6) | |
(* Optional arguments using defaults *) | |
let _ = | |
let f ?(x=0) ?(y=0) () = x + y in | |
(* f : ?x:int -> ?y:int -> unit -> int *) | |
printf "%d\n" (f ~x:5 ~y:6 ()); | |
printf "%d\n" (f ~x:5 ()); | |
printf "%d\n" (f ~y:6 ()) | |
let _ = | |
let f ?(x=0) ?(y=0) = x + y in | |
printf "%d\n" (f ~x:5 ~y:6) | |
(* The compiler will reject these because it can't tell where the "last" argument is *) | |
(* printf "%d\n" (f ~x:5); *) | |
(* printf "%d\n" (f ~y:6) *) | |
(* If you leave off the default, OCaml will assume optional arguments | |
are wrapped in an option type, where None indicates the caller left | |
it off. *) | |
let _ = | |
let f ?x ?y () = | |
match x,y with | |
| Some x', Some y' -> x' + y' | |
| Some x', None -> x' | |
| None, Some y' -> y' | |
| None, None -> 0 | |
in | |
(* f : ?x:int -> ?y:int -> unit -> int *) | |
(* The type is the same, which seems bizarre. Within the body of f, | |
x has type option int, not int. But from the caller's | |
perspective, the optional argument has type int, and the caller's | |
perspective is what matters. *) | |
printf "%d\n" (f ~x:5 ~y:6 ()); | |
printf "%d\n" (f ~x:5 ()); | |
printf "%d\n" (f ~y:6 ()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment