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:
_of_ where and are int, float, string
float_of_int(42)
variable binding:
let =
let x = 2 + 3 * 5
conditional:
if then else
if x < y then x else y
simple function
let () =
let sum(a, b) = a + b
recursive function
let rec () =
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 in
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 with match lst with
| -> | [] -> invalid_arg("empty list")
| -> | [x] -> x
... | x::xs -> last(xs)
| ->
anonymous functions
fun ->
let double = fun x -> 2 * x
partially instantiated function
let double = ( * ) 2