cheatsheet
cheatsheet
() : unit List.fold_left : ('a->'b->'a) -> 'a -> 'b list -> 'a
3 : int List.fold_left (^) "x" ["a";"b";"c"] "xabc"
3.0 : float
'A' : char List.find : ('a -> bool) -> 'a list -> 'a
"xyz" : string List.find (fun x -> x > 10) [1;5;10;13;19] 13
false : bool List.find (fun x -> x > 10) [1;5;10] raises Not_found
3 < 5 && true : bool
Some 3 : int option String.length "hello" 5
None : 'a option List.length [8; 9; 10] 3
ref 3 : int ref List.rev [8; 9; 10] [10; 9; 8]
[3; 4] : int list List.nth [8; 9; 10] 2 10
[] : 'a list List.nth [8; 9; 10] 3 raises Failure "nth"
(2, "xyz", 3.0) : int * string * float
fun x -> x + 1 : int -> int let (x, y) = (Some 111, 2999) in
fun x y -> x + y : int -> int -> int match (x, y) with
fun (x, y) -> x + y : int * int -> int (Some z, _) -> z + y
fun () -> 4 : unit -> int | (None, _) -> y 3110
Not_found : exn
let e = exp 1. in
if x < 0 || x > 0 let pi = 2. *. asin 1. in
then "nonzero" (e, pi) (2.7182818284590451, 3.1415926535897931)
else "zero"
let uncurried (x, y) = x + y in
match x with let curried x y = x + y in
0 -> "zero" (uncurried (1, 2), curried 1 2) (3, 3)
| 1 -> "one"
| _ -> "more than one" let rec sum (x : int list) : int =
match x with
Char.code 'a' 97 [] -> 0
Char.code 'A' 65 | u :: t -> u + sum t
Char.code '0' 48
Char.chr 97 'a' module type STACK = sig
type 'a stack
(fun x -> x + 1) 3 4 exception Empty of string
"x" ^ "y" ^ "z" "xyz" val make : unit -> 'a stack
-5 + 7 2 val push : 'a stack * 'a -> 'a stack
val pop : 'a stack -> 'a * 'a stack
let compose f g x = f (g x) in val isEmpty : 'a stack -> bool
let f x = x * x in end
let ff = compose f f in
let fff = compose f ff in module Stack : STACK = struct
(f 2, ff 2, fff 2) (4, 16, 256) type 'a stack = 'a list
exception Empty of string
List.hd [3; 4] 3 let make () = []
List.tl [3; 4] [4] let push (s, x) = x :: s
List.tl [4] [] let pop s =
3 :: [4; 5] [3; 4; 5] match s with
[1;2;3] @ [4;5;6] [1;2;3;4;5;6] x :: t -> (x, t)
| [] -> raise (Empty "empty")
fst (2, "abc") 2 let isEmpty = fun x -> x = []
snd (2, "abc") "abc" end
type 'a option = Some of 'a | None let xr : int ref = ref 2999 in
type 'a stack = Empty | Top of ('a * 'a stack) xr := !xr + 111 ()
Top (3, Empty) : int stack sets xr to 3110 as a side effect
type rcrd = {foo:int; bar:string}
{foo=3; bar="xyz"} : rcrd (print_endline "hello"; 3110) 3110
prints "hello" as a side effect
List.map : ('a -> 'b) -> 'a list -> 'b list
List.map (fun x -> x + 100) [2;3;4] [102;103;104] try Some (List.find (fun x -> x > 10) [1;5;10])
List.map (fun x -> x = 3) [2;3;4] [false;true;false] with Not_found -> None None
List.filter : ('a -> bool) -> 'a list -> 'a list raise Not_found
List.filter (fun x -> x < 4) [4;3;9;6;1;0;5] [3;1;0]
raise (Failure "error")
List.fold_right: ('a->'b->'b) -> 'a list -> 'b -> 'b failwith "error"
List.fold_right (^) ["a";"b";"c"] "x" "abcx"