CSE341 Midterm Cheat Sheet Data Type Example Operators/Functions ------------------------------------------------------------------------------- integers int 42 + - * / mod abs reals float 17.5 +. -. *. /. abs_float booleans bool true && || not < > <= >= = <> strings string "hello" ^ String.length String.sub s.[i] characters char 'a' lists list of t [17; 2; 5] List.hd List.tl List.length :: @ List.map List.filter List.fold_left List.fold_right tuples t1 * t2... (12, "abc") type conversion functions: <x>_of_<y> where <x> and <y> are int, float, string float_of_int(42) variable binding: let <identifier> = <expression> let x = 2 + 3 * 5 conditional: if <boolean expression> then <expression> else <expression> if x < y then x else y simple function let <name>(<parameters>) = <expression> let sum(a, b) = a + b recursive function let rec <name>(<parameters>) = <expression> let rec factorial(n) = if n = 0 then 1 else n * factorial(n - 1) example of nested if/else let signum(n) = if n < 0 then -1 else if n = 0 then 0 else 1 let expression (unlike let definition, this returns a value) let <binding> in <expression> let x = 0.35 in x *. x *. x *. x examples of pattern match with let expressions: let x = (3.4, "hello") x bound to the tuple let (x, y) = (3.4, "hello") x bound to 3.4, y bound to "hello" let [x] = [3] x bound to 3 let x::xs = [1; 3; 5] x bound to 1 (hd), y bound to [3; 5] (tl) let x::y::zs = [1; 3; 5] x bound to 1, y bound to 3, zs bound to [5] match expression let rec last(lst) = match <expression> with match lst with | <pattern> -> <expression> | [] -> invalid_arg("empty list") | <pattern> -> <expression> | [x] -> x ... | x::xs -> last(xs) | <pattern> -> <expression> anonymous functions fun <parameters> -> <expression> let double = fun x -> 2 * x partially instantiated function let double = ( * ) 2
Stuart Reges
Last modified: Mon Apr 22 11:53:13 PDT 2024