Académique Documents
Professionnel Documents
Culture Documents
Jed Liu
Department of Computer Science
Cornell University
CS 6110 Lecture
26 January 2009
Based on CS 3110 course notes
and an SML tutorial by Mike George
Jed Liu
Introduction to OCaml
Installing OCaml
I
Linux:
yum install ocaml
apt-get install ocaml
emerge dev-lang/ocaml
Windows:
http://caml.inria.fr/ocaml/release.en.html
Jed Liu
Introduction to OCaml
Declaring Variables
Jed Liu
Introduction to OCaml
Base Types
let
let
let
let
let
I
I
I
x
y
z
w
v
:
:
:
:
:
int = -7
char = a
string = "moo"
float = 3.14159
bool = true
Jed Liu
Introduction to OCaml
Jed Liu
Introduction to OCaml
More Datatypes
(* Datatype constructors
(* and be recursive (and
type var = string
type exp = Var of var
| Lam of var *
| App of exp *
exp
exp
Introduction to OCaml
Pattern Matching
let t1 : int * int = ...
(* Binds two variables at once *)
let (a, b) = t1
(* Use _ for "dont care" *)
let (_, b) = t1
(* Can match constants too *)
let (a, 5) = t1
I
Jed Liu
Introduction to OCaml
Jed Liu
Introduction to OCaml
Introduction to OCaml
Jed Liu
Introduction to OCaml
I
I
Introduction to OCaml
Functions
Jed Liu
Introduction to OCaml
Recursive Functions
Jed Liu
Introduction to OCaml
10
More Functions
Jed Liu
Introduction to OCaml
11
More Functions
Jed Liu
Introduction to OCaml
11
Curried Functions
let rec gcd (a, b) : int =
if b = 0 then a
else gcd (b, a mod b)
(* Preferred style: *)
let rec gcd (a:int) (b:int) : int =
if b = 0 then a
else gcd b (a mod b)
(* Has type int -> int -> int *)
(* More explicitly: *)
let rec gcd (a:int) : int -> int =
fun (b:int) ->
if b = 0 then a
else gcd b (a mod b)
Jed Liu
Introduction to OCaml
12
A Minor Tangent...
I
We have
gcd : int * int -> int
gcd: int -> (int -> int)
Through currying and uncurrying, these types
are somehow equivalent
Squint hard and you might see logical
propositions...
A B = C
A = (B = C )
...which are logically equivalent!
Jed Liu
Introduction to OCaml
13
Local Declarations
Jed Liu
Introduction to OCaml
14
Polymorphism
(* What is this functions type? *)
let id x = x
Jed Liu
Introduction to OCaml
15
Polymorphism
(* What is this functions type? *)
let id x = x
(* More explicitly *)
let id (x : a) : a = x
(* A polymorphic datatype *)
type a lst =
Empty
| Cons of (a * a lst)
let rec map (f:a -> b) (l:a lst) : b lst =
match l with
Empty -> Empty
| Cons (hd, tl) -> Cons (f hd, map f tl)
Jed Liu
Introduction to OCaml
15
Lists
I
Introduction to OCaml
16
Jed Liu
Introduction to OCaml
17
Summary
I
I
I
Jed Liu
Introduction to OCaml
18
Resources
CS 3110 notes
http://www.cs.cornell.edu/courses/cs3110/2008fa/
OCaml manual
http://caml.inria.fr/pub/docs/manual-ocaml/
Jed Liu
Introduction to OCaml
19