(* construct a list *) let l = 1 :: [] in let l = [ 1 ; 2; 3 ] in let l = [ 1 ] @ [ 2 ; 3 ] in let l = 1 :: 2 :: 3 :: [] in let fst::rest = l in let fst::snd::third::rest = l in
let third = List.nth 2 [1 ;2 ;3] in let squares = List.map (fun x -> x * x) [ 1 ; 2 ; 3] in let sum = List.fold_left (+) 0 [ 1 ; 2 ; 3] in let product = List.fold_left ( * ) 1 [ 1 ; 2 ; 3] in let gt4 = List.map ( fun x -> (x, x > 4) ) [ 1 ; 2 ; 3 ; 4 ; 5; 6 ] in let gt4 = List.filter (fun x -> x > 4) [2 ; 4 ; 6; 8] in let tf = List.exists (fun x -> 10 = x) [ 1 ; 2 ; 10] in
let third = Array.nth 2 [| 1 ;2 ;3 |] in let squares = Array.map (fun x -> x * x) [| 1 ; 2 ; 3 |] in let sum = Array.fold_left (+) 0 [| 1 ; 2 ; 3 |] in let product = Array.fold_left ( * ) 1 [| 1 ; 2 ; 3 |] in let gt4 = Array.map ( fun x -> (x, x > 4) ) [| 1 ; 2 ; 3 ; 4 ; 5; 6 |] in let gt4 = Array.filter (fun x -> x > 4) [| 2 ; 4 ; 6; 8 |] in let tf = Array.exists (fun x -> 10 = x) [| 1 ; 2 ; 10 |] in
let f x = x in let f (a,b) = (b,a) in let f = (* closure *) let x = 9 in (fun y -> y * x) in let rec f n = if (n > 0) then f (n - 1) else n in
(* lets use pattern matching *) let rec f = function 0 -> 0 | n -> f (n - 1) in
let res = if (cond) then value1 else value2 in let res = match x where x::xs -> Some (x::xs) (* pattern matching *) | [] -> None in let not_none = match x where None -> false | _ -> true in
let a = (x,y) ;; (* tuples can be of mixed types *) type color = { r : int ; g : int ; b : int };; let b = { r = 1.0 ; g = 0.5; b = 0.5 } ;; (* structs *) type cheese = Cheese of string;; let c = Cheese(``Havarti'');; type coord = ((a:int) * (b:int));;
type pizza = Crust of pizza | Pepperoni | Olives | Cheese of pizza list ;; let pizza = Crust(Cheese( [ Pepperoni ; Olives ; Crust(Pepperoni)] ));; let rec just_crust_and_cheese = function Crust(x) -> just_crust_and_cheese x | Cheese([]) -> true | Cheese(x) -> List.for_all just_crust_and_cheese x | _ -> false ;; just_crust_and_cheese (Crust(Cheese([])));; just_crust_and_cheese pizza;;
type foo = { num : int; mutable name: string }
let i = ref 0
(* deref i and add 1 to it and assign it *) i := !i + 1; array.(!i) <- !i; (* array assn *) (* assign a value to an entry in a struct *) f.name <- ``lolcakes'';
let fabs (x:float) = if x >= 0. then x else (-1.0) *. x in