0% found this document useful (0 votes)
50 views45 pages

Lec2 Crash

The document provides an introduction to the OCaml programming language. It discusses OCaml's static type system and how expressions are compiled and evaluated. It covers complex types like lists, functions, pattern matching, and variables. Functions can take functions as arguments and return functions. Examples demonstrate filtering, partitioning, and quicksorting lists using functional patterns.

Uploaded by

kakashi116
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views45 pages

Lec2 Crash

The document provides an introduction to the OCaml programming language. It discusses OCaml's static type system and how expressions are compiled and evaluated. It covers complex types like lists, functions, pattern matching, and variables. Functions can take functions as arguments and return functions. Examples demonstrate filtering, partitioning, and quicksorting lists using functional patterns.

Uploaded by

kakashi116
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

OCaml

The PL for the discerning hacker.

Hello! My name is Zach.

Ill be your guide for today.


2

ML Flow
Expressions (Syntax) Compile-time Static Exec-time Dynamic Values (Semantics)

Types

1. Enter expression 2. ML infers a type

Typing -> Eval Always Works

3. ML crunches expression down to a value 4. Value guaranteed to have type

Complex types: Lists


[]; [1;2;3]; [1+1;2+2;3+3;4+4]; [a;b; c^d]; [(1,a^b);(3+4,c)]; [[1];[2;3];[4;5;6]]; [] [1;2;3] [2;4;6;8] [a;b; cd] [(1,ab);(7,c)] [[1];[2;3];[4;5;6]];
a list int list int list string list (int*string) list (int list) list

Unbounded size Can have lists of anything (e.g. lists of lists) But
5

Complex types: Lists


[1; pq];

All elements must have same type

Question 1
Which of these causes a type error? (a) [1; 2; 3] (b) [1, 2, 3] (c) [1; 2; 3] (d) (1, 2, 3) (e) [1; 2; 3]
7

Complex types: Lists


List operator Cons
1::[]; 1::[2;3]; a::[b;c];

::
[1] [1;2;3] [a;b;c]
int list int list string list

Can only cons element to a list of same type 1::[b; cd];

Lists: Construct
Nil operator
[] []:a list [] => []

Cons operator
1::[2;3]
int list

[1;2;3]

e1:T e2: T list e1::e2 : T list

e1=>v1 e2=> v2 e1::e2 => v1::v2


9

Complex types: Lists


List operator Append
[1;2]@[3;4;5]; [a]@[b]; []@[1];

@
[1;2;3;4;5] [a;b] [1]
int list string list int list

Can only append two lists of the same type

1 @ [2;3];

[1] @ [a;b];

10

Complex types: Lists


List operator head
hd [1;2]; hd ([a]@[b]);

hd
1 a
int string

Only take the head a nonempty list

hd [];

11

Complex types: Lists


List operator tail
tl [1;2;3]; tl ([a]@[b]);

tl
[2;3] [b]
int list string list

Only take the tail of nonempty list

tl [];

12

Question 2: What is result of?


(hd [[];[1;2;3]]) = (hd [[];[a]])

(a) Syntax Error (b) true : bool (c) false : bool (d) Type Error (hd) (e) Type Error (=)

13

Lists: Deconstruct
Head Tail
e :T list hd e : T e => v1::v2 hd e => v1

e :T list tl e : T list

e => v1::v2 tl e => v2

(hd [[];[1;2;3]]) = (hd [[];[a]])


int list

e 1: T e 2 : T e1=e2 : bool

string list

14

Recap: Tuples vs. Lists ?


Whats the difference ? Tuples:
Different types, but fixed number:
(3, abcd)
pair = 2 elts

(int * string) (int * string * (float * float))

(3, abcd,(3.5,4.2))
triple = 3 elts

Lists:
Same type, unbounded number:
[3;4;5;6;7] int list

Syntax:
Tuples = comma Lists = semicolon
15

So far, a fancy calculator

what do we need next ?

16

So far, a fancy calculator

Branches
17

Question 3: What is result of?


if (1 < 2) then true else false (a) Syntax Error (b) true (c) false (d) Type Error

18

Question 4: What is result of?


if (1 < 2) then [1;2] else 5 (a) Syntax Error (b) [1;2] (c) 5 (d) Type Error

19

If-then-else expressions
e1 : bool e2: T e3: T if e1 then e2 else e3 : T

Then-subexp, Else-subexp must have same type!


Equals type of resulting expression if 1>2 then [1,2] else [] []
int list

if 1<2 then [] else [a] []


string list

(if 1>2 then [1,2] else [])=(if 1<2 then [] else [a])

20

If-then-else expressions
if (1 < 2) then [1;2] else 5 if false then [1;2] else 5

then-subexp, else-subexp must have same type!


which is the type of resulting expression

e1

: bool e2: T e3: T if e1 then e2 else e3 : T

21

So far, a fancy calculator

Variables
22

Question 5: I got this @ prompt


# [x+x; x*x] ;; - : int list = [20; 100] What had I typed before? (a) x = 10; (b) int x = 10; (c) x == 10; (d) let x = 10; (e) x := 10;
23

Variables and bindings

let x = e;;
Bind the value of expression

to the variable

# let x = 2+2;; val x : int = 4


24

Variables and bindings


Later declared expressions can use

Most recent bound value used for evaluation


# let val x # let val y # let val z # x : y : z : = 2+2;; int = 4 = x * x * x;; int = 64 = [x;y;x+y];; int list = [4;64;68]

25

Variables and bindings


Undeclared variables (i.e. without a value binding) are not accepted !
# let p = a + 1; Characters 8-9: let p = a + 1 ;; ^ Unbound value a

Catches many bugs due to typos


26

Local bindings
for expressions using temporary variables
let tempVar = x + 2 * y in tempVar * tempVar ;;

17424

int

tempVar is bound only inside expr body from in Not visible (not in scope) outside

27

Question 6: What is result of?


let x = 10 in (let z = 10 in x + z) + z (a) Syntax Error (b) 30 (c) Unbound Error -- x (d) Unbound Error -- z (e) Type Error
28

Binding by Pattern-Matching
Simultaneously bind several variables
# let (x,y,z) = (2+3,a^b, 1::[2]);; val x : int = 5 val y : string = ab val z : int list = [1;2]

29

Binding by Pattern-Matching
But what of:
# let h::t = [1;2;3];; Warning P: this pattern-matching not exhaustive. val h : int = 1 val t : int list = [2;3]

Why is it whining ?
# let h::t = []; Exception: Match_failure # let XS = [1;2;3]; val xs = [1;2;3]: list - val h::t = xs; Warning: Binding not exhaustive val h = 1 : int val t = [2;3] : int

In general

xs may be empty (match failure!)


30

Another useful early warning

Binding by Pattern-Matching
But what of:
# let h::t = [1;2;3];; NEVER USE PATTERN MATCHING Warning P: this pattern-matching not exhaustive. val h : int = 1 LIKE THIS val t : int list = [2;3]

Why is it whining ?

let h::t = ...

In general

# let h::t = []; Exception: Match_failure ALWAYS USE THIS FORM INSTEAD # let XS = [1;2;3]; val xs = [1;2;3]: list - val h::t = xs; match l with ... Warning: Binding not exhaustive val h = 1 : int val (coming t = [2;3] int but this is important) up:soon,

xs may be empty (match failure!)

Another useful early warning


31

Functions
32

Functions up now, remember


Expression Value

Type
Everything is an expression Everything has a value Everything has a type

A function is a value!

33

Complex types: Functions!


Parameter (formal) Body Expr fn int -> int
# let inc = fun x -> x+1 ; val inc : int -> int = fn # inc 0; val it : int = 1 # inc 10; val it : int = 11

fun x -> x+1;;

34

A Problem
Parameter (formal) Body Expr fn int -> int

fun x -> x+1;;

Functions only have ONE parameter ?!

How a call (application) is evaluated: 1. Evaluate argument 2. Bind formal to arg value 3. Evaluate Body expr

35

A Solution: Simultaneous Binding


Parameter (formal) Body Expr fn

fun (x,y) -> x<y; (int * int) -> bool

Functions only have ONE parameter ?

How a call (application) is evaluated: 1. Evaluate argument 2. Bind formal to arg value 3. Evaluate Body expr

36

Another Solution (Currying)


Parameter (formal) Body Expr fn fun x -> fun y-> x<y; int -> (int -> bool)

Whoa! A function can return a function


# let lt = fun x -> fun y -> x < y ; val lt : int -> int -> bool = fn # let is5Lt = lt 5; val is5lt : int -> bool = fn; # is5lt 10; val it : bool = true; # is5lt 2; val it : bool = false;
37

Question 7: What is result of?


(fun x -> not x) (a) Syntax Error (b) <fun> : int -> int (c) <fun> : int -> bool (d) <fun> : bool -> int (e) <fun> : bool -> bool
38

And how about


Parameter (formal) Body Expr fn fun f -> fun x -> not(f x); (a ->bool) -> (a -> bool)

A function can also take a function argument


# let neg = fun f -> fun x -> not (f x);
val lt : int -> int -> bool = fn # let is5gte = neg is5lt; val is5gte : int -> bool = fn # is5gte 10; val it : bool = false; # is5gte 2; val it : bool = true; (*odd, even *)

39

Question 8: What is result of?


(fun f -> (fun x -> (f x)+x)) (a) Syntax Error (b) Type Error (c) <fun> : int -> int -> int (d) <fun> : int -> int (e) <fun> : (int->int)-> int -> int
40

A shorthand for function binding


# let neg = fun f -> fun x -> not (f x);
# let neg f x = not (f x); val neg : int -> int -> bool = fn # let is5gte = neg is5lt; val is5gte : int -> bool = fn; # is5gte 10; val it : bool = false; # is5gte 2; val it : bool = true;

41

Put it together: a filter function


If arg matches this pattern
- let rec filter f xs match xs with | [] -> [] | (x::xs)-> if f then else

then use this Body Expr


= x x::(filter f xs) (filter f xs);;

val filter : (a->bool)->a list->a lisi) = fn # let list1 = [1;31;12;4;7;2;10];; # filter is5lt list1 ;; val it : int list = [31;12;7;10] # filter is5gte list1;; val it : int list = [1;4;2] # filter even list1;; val it : int list = [12;4;2;10]
42

Put it together: a partition function

# let partition f l = (filter f l, filter (neg f) l); val partition :(a->bool)->a list->a list * a list = fn

# let list1 = [1,31,12,4,7,2,10]; - # partition is5lt list1 ; val it : (int list * int list) = ([31,12,7,10],[1,2,10] # partition even list1; val it : (int list * int list) = ([12,4,2,10],[1,31,7])

43

A little trick
# 2 <= 3;;
val it : bool = true # ba <= ab;; val it : bool = false # let lt = (<) ;; val it : a -> a -> bool = fn # lt 2 3;; val it : bool = true; # lt ba ab ;; val it : bool = false;

# let is5Lt = lt 5; val is5lt : int -> bool = fn; # is5lt 10; val it : bool = true; # is5lt 2; val it : bool = false;
44

Put it together: a quicksort function


let rec sort xs = match xs with | [] -> [] | (h::t) -> let (l,r) = partition ((<) h) t in (sort l)@(h::(sort r))

Now, lets begin at the beginning


45

You might also like