Tutorial by Examples

Values can be given names using let: # let a = 1;; val a : int = 1 You can use similar syntax to define a function. Just provide additional parameters for the arguments. # let add arg1 arg2 = arg1 + arg2;; val add : int -> int -> int = <fun> We can call it like this: # add 1...
The function keyword automatically has pattern matching when you define the body of your function. Observe it below: # let foo = function 0 -> "zero" | 1 -> "one" | 2 -> "couple" | 3 -> "few" | _ -> "many";; val foo : int -&gt...
Since functions are ordinary values, there is a convenient syntax for creating functions without names: List.map (fun x -> x * x) [1; 2; 3; 4] (* - : int list = [1; 4; 9; 16] *) This is handy, as we would otherwise have to name the function first (see let) to be able to use it: let square x...
You can define a function to be recursive with the rec keyword, so it can call itself. # let rec fact n = match n with | 0 -> 1 | n -> n * fact (n - 1);; val fact : int -> int = <fun> # fact 0;; - : int = 1 # fact 4;; - : int = 24 You can also define mutually re...

Page 1 of 1