Oct 31 2010
Functional OCaml Cheatsheet
Having learned functional OCaml during CSE 130 (btw, Prof. Lerner is great), here’s a version of my midterm notes for future reference (unfortunately, without syntax highlighting; I can’t find a SyntaxHighlighter brush for OCaml):
(* An OCaml comment. (* You can nest them. *) *)
Some infix operators:
Equality: = (*though also used in Let-In for assignment*)
Inequality: !=
String concatenation: ^
Integer modulo: mod
Floating-point arithmetic: /. +. -. (* etc.; they all have extra periods*)
(* Let-In expressions *)
(* Vaguely imperative, less-indented style *)
let x = q in
let y = w in
q + w
(* Functional, more-indented style *)
let x = q in
let y = w in
x + y
(* Using tuple unpacking *)
let x, y = q, w in x + y (* we're not concerned with indents in this example *)
If-Then-Else:
if x then y else z
Lists:
[] (* Empty list*)
[1; 2; 3; 4] (* List literal *)
x::xs (* Cons operator *)
xs @ ys (* List concatenation operator *)
Tuples:
let triple = (x, y, z) ;;
Tuple types are *-separated and parenthesized: (a * b * c)
Functions:
(* Named functions *)
let add x y = x + y ;;
(* Anonymous functions; "lambda"s *)
let otherwise_nameless_add = fun x y -> x + y ;;
(* Recursive functions *)
let rec factorial = if n <= 1 then 1 else n*(factorial n-1)
(* The "rec" is required; you can also include it harmlessly when declaring non-recursive functions. *)
Algebraic datatypes:
type expr =
| VariableX
| Negative of expr
| Plus of expr * expr
(* Calling constructors *)
let sum = Plus(VariableX, VariableX) ;;
(* Declaring a generic ADT *)
type 'a list =
| Nil
| Cons of 'a * 'a list
Pattern matching
let as_string sum =
match sum with
| VariableX -> "x" (* Yes, you could leave the "|" out for the first case, but I find that annoyingly irregular. *)
| Negative(ex) -> "-" ^ (as_string ex)
| Plus(left,right) -> "(" ^ (as_string left) ^ " + " ^ (as_string right) ^ ")"
Parens are unfortunately often necessary for nested match-es.
Types of somewhat interesting functions:
List.map: ('a -> 'b) -> 'a list -> 'b list
List.left_fold: ('a -> 'b -> 'a ) -> 'a -> 'b list -> 'a
(* accum list item new accum init result
(----------"reducer"---------*)
Popularity: 13% [?]
No responses yet
In the Quest of the Fragrant Harbour
Lacey Thoughts
League of Desmond