In a strict language a value is computed where it is written. In this block we put a function in its place.
| 1 | Thunks when? | We choose when the value is computed: when we call the function. |
| 2 | Sequences how far? | We put the function inside a data structure. We choose how far a sequence is computed, and it can be without end. |
| 3 | Memoisation how many times? | We keep the result of the function. We choose that the value is computed at most once. |
if written as a functionlet my_if c t e = if c then t else e
let rec fact n =
my_if (n = 0) 1 (n * fact (n - 1))
fact 5 never returns. OCaml computes the two branches before it calls my_if.
let my_if c t e = if c then t () else e ()
let rec fact n =
my_if (n = 0) (fun () -> 1)
(fun () -> n * fact (n - 1))
fact 5 is 120. my_if calls one of the two functions.
fun () -> e.
What does the program print, and in which order?
The same program in OCaml
OCamllet t = fun () ->
print_endline "computing";
6 * 7
let () = print_endline "the thunk is made"
let a = t ()
let b = t ()
let rec fold_left f acc xs =
match xs with
| [] -> acc
| x :: xs -> fold_left f (f acc x) xs
Our function receives the accumulator and one element. The rest of the list, xs, stays with the fold.
let rec fold_right f xs z =
match xs with
| [] -> z
| x :: xs -> f x (fold_right f xs z)
Our function receives one element and the fold of the rest, as its second argument.
fold_right keeps one frame waiting per element; fold_left keeps none: its recursive call is a tail call.
exists, with the left foldOCamllet exists p l = fold_left (fun found x -> found || p x) false l
exists (fun c -> c = '\n') text
exists, with the right foldOCamllet exists p l = fold_right (fun x rest -> p x || rest) l false
exists (fun c -> c = '\n') text
let rec fold_right f xs z = match xs with
| [] -> z
| x :: xs ->
f x (fun () -> fold_right f xs z)
OCamllet exists p l =
fold_right
(fun x rest -> p x || rest ())
l false
OCamllet rec from n = n :: from (n + 1)
let rec take n l =
if n = 0 then []
else match l with
| [] -> []
| x :: rest -> x :: take (n - 1) rest
take 5 (from 0)
Stack overflow during evaluation
Haskellfrom n = n : from (n + 1)
take n l =
if n == 0 then []
else case l of
[] -> []
x : rest -> x : take (n - 1) rest
take 5 (from 0)
[0,1,2,3,4]
The two programs are the same, line for line. Why does Haskell give an answer, and OCaml none?
take 5 (from 0) -- Haskell also writes from 0 as [0 ..]
take 5 reads five cells, so five cells are built.Haskellprimes = sieve [2 ..]
where sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p /= 0]
| in Haskell | we read | as we know it |
|---|---|---|
[2 ..] | the list 2, 3, 4, … without end | from 2 |
p : xs | a list: its first element p, its rest xs | OCaml: p :: xs |
[x | x <- xs, c] | the list of the x of xs for which c holds | Python: [x for x in xs if c] |
x `mod` p /= 0 | x is not a multiple of p | OCaml: x mod p <> 0 |
where | a definition written after its use | OCaml: let … in, before |
sieve keeps p, the first element, and calls itself on the rest without the multiples of p. The list in brackets is block 1's filter.take k primes: how far is [2 ..] built?take 10 primes = [2,3,5,7,11,13,17,19,23,29]
The sieve is applied to a list without end, and it calls itself on a list without end. Why does the program end?
take 1 primes | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | … |
take 2 primes | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | … |
take 3 primes | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | … |
take 4 primes | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | … |
take 5 primes | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | … |
A number is struck out when a prime kept before it divides it. To give its first k primes, Haskell builds [2 ..] up to the k-th prime: the hatched numbers are not yet computed.
In Haskell no argument is computed before the call. It is computed when the function uses it, and at most once: session 4's call-by-need.
| in OCaml, we write | in Haskell | |
|---|---|---|
| Block 1 | another fold, to stop before the end of a list | the right fold stops by itself |
| Block 2 | a thunk for each value that must wait | every value waits, and is computed once |
| Session 6 | two functions, for a search that can fail | the list of all the solutions, of which we read the first |
Haskellfoldr (\x rest -> x > 2 || rest)
False [0 ..]
True
foldr f False [0 ..]
= f 0 (foldr f False [1 ..])
= …
= f 3 (foldr f False [4 ..])
= True
The call on top is f, our function. At 3 it answers, and does not read its rest.
foldl (\found x -> found || x > 2)
False [0 ..]
the program does not end
foldl f False [0 ..]
= foldl f (f False 0) [1 ..]
= foldl f (f (f False 0) 1) [2 ..]
= foldl f (f (f (f False 0) 1) 2) [3 ..]
= …
The call on top is always foldl: no step answers. The calls of f wait, and are never run.
type 'a list =
| []
| (::) of 'a * 'a list
The rest of a list is a list: a value. It is computed before we read the first element.
type 'a node =
| Nil
| Cons of 'a * 'a seq
and 'a seq = unit -> 'a node
The rest of a sequence is a thunk. It is computed when we call it.
* CS3110, section 9.4. OCaml's library has this type as Seq.t.
nats and takeOCamllet rec nats n : int seq =
fun () -> Cons (n, nats (n + 1))
let rec take n (s : 'a seq) =
if n = 0 then []
else match s () with
| Nil -> []
| Cons (x, rest) ->
x :: take (n - 1) rest
nats 0 is the sequence of all the natural numbers.
What does take 5 (nats 0) compute, and how many elements of nats 0?
[0; 1; 2; 3; 4] produced=5
nats 3, is a thunk that nobody has called.map and filter on a sequenceOCamllet rec map f (s : 'a seq) : 'b seq =
fun () -> match s () with
| Nil -> Nil
| Cons (x, rest) ->
Cons (f x, map f rest)
map f s returns at once: its body is under fun () ->.
let rec filter p (s : 'a seq) : 'a seq =
fun () -> match s () with
| Nil -> Nil
| Cons (x, rest) ->
if p x
then Cons (x, filter p rest)
else filter p rest ()
When x does not pass, filter asks for the next element itself.
Cons, the recursive call returns at once: it makes a function that nobody has called yet. The rest is computed when the consumer asks for it.OCamllet even n = n mod 2 = 0
let square n = n * n
let squares =
map square (filter even (nats 0))
produced=0
take 5 squares
[0; 4; 16; 36; 64] produced=9
How many elements has nats 0 produced when squares is defined? And after take 5?
Nine numbers, from 0 to 8. Five of them are even.
squares computes no element. The consumer decides how far it is computed.take 5 squares, step by stepOCamllet rec exists p (s : 'a seq) =
match s () with
| Nil -> false
| Cons (x, rest) ->
p x || exists p rest
The text of block 1, hi\nyo, as a sequence of characters:
exists (fun c -> c = '\n') text
found=true asked=3
SeqOCamlSeq.ints 0
|> Seq.filter (fun n -> n mod 2 = 0)
|> Seq.map (fun n -> n * n)
|> Seq.take 5
|> List.of_seq
[0; 4; 16; 36; 64]
Seq.t is the type that we wrote, and Seq.ints 0 is our nats 0.
x |> f is f x. With it the line reads in the order the elements travel, from ints to take, and not from the inside out.
OCamllet ticks = ref 0
let t = fun () -> incr ticks; 6 * 7
let a = t ()
let b = t ()
a=42 b=42 ticks=2
let ticks = ref 0
let l = lazy (incr ticks; 6 * 7)
let a = Lazy.force l
let b = Lazy.force l
a=42 b=42 ticks=1
What is !ticks at the end of each program?
Okasaki 1998, chapter 4: a stream is part 2's sequence with a lazy value, not a thunk, for the rest.
lazy, made by handOCamltype 'a state =
| Delayed of (unit -> 'a)
| Value of 'a
let delay f = ref (Delayed f)
let force s = match !s with
| Value v -> v
| Delayed f ->
let v = f () in
s := Value v;
v
A lazy value is a reference that holds a thunk, and after the first force the value.
let s = delay (fun () ->
incr ticks; 6 * 7)
let a = force s
let b = force s
a=42 b=42 ticks=1
delay we write the fun () -> ourselves. lazy e is a keyword: a function would receive e already computed.Haskellfibs = 0 : 1 : zipWith (+) fibs (tail fibs)
fibs: how many additions?OCamltype 'a node = Nil | Cons of 'a * 'a seq
and 'a seq = 'a node Lazy.t
(* zip_with and tail read their sequences with Lazy.force *)
let rec fibs = lazy (Cons (0, lazy (Cons (1, zip_with ( + ) fibs (tail fibs)))))
The same list in OCaml. To compute its first 25 numbers, how many additions are needed?
| the rest of the sequence is | additions |
|---|---|
| a thunk, in OCaml | 196 392 |
a lazy value, in OCaml | 23 |
| a list, in Haskell | 23 |
lazy, fibs and tail fibs share the numbers. In Haskell every value is lazy, by default.OCamllet pop = function
| x :: front, rear ->
Some (x, (front, rear))
| [], rear ->
match rev rear with
| [] -> None
| x :: front ->
Some (x, (front, []))
Lab 2's queue, as we wrote it there: a front and a rear. When the front is empty, pop reverses the rear.
(* q: eight elements pushed *)
let a = pop q
let b = pop q
a=1 b=1 reversals=2
q can be used twice. With this pop, the reversal is then paid twice.lazy the reversal is suspended inside q: the two pops share it, and it is paid once. We write that queue as homework, at the end of the warm-up's sheet.Source: Okasaki 1998, chapter 6, the banker's queue.
| the question | the program decides, in OCaml | the language decides, in Haskell | |
|---|---|---|---|
| 1 | When is a value computed? | When we call the thunk that holds it. | When it is used. |
| 2 | How far is a sequence computed? | As far as we ask: a sequence. | Every list is a sequence. |
| 3 | How many times? | Once, if we keep the result: lazy. | Once: every value is lazy, by default. |
unit -> 'a. We call it to get a value.'a -> 'r. We call it to give a value.Session 6: a promise is a value that is not there yet, together with what to do when it arrives.
fib 25, without memoisationOCamllet rec fib n =
if n < 2 then n
else fib (n - 1) + fib (n - 2)
let a = fib 25
let b = fib 25
a=75025 b=75025 the body ran 485570 times
The second call computes everything again: a function keeps nothing from one call to the next.
With lazy (fib 25) we keep one result, for the argument 25. Every other argument needs a lazy value of its own.
memo: a function that keeps a tableOCamllet memo f =
let table = Hashtbl.create 16 in
fun x ->
match Hashtbl.find_opt table x with
| Some y -> y
| None ->
let y = f x in
Hashtbl.add table x y;
y
memo f makes a table, once, and returns a function.
x, the function looks x up in the table.f is not called.f, keeps the result, and returns it.lazy is the same with one entry: the table of a function of no argument.memo fib: the calls that the table seesOCamllet rec fib n =
if n < 2 then n
else fib (n - 1) + fib (n - 2)
let mfib = memo fib
| result | the body of fib ran | |
|---|---|---|
mfib 25 | 75025 | 242 785 times |
mfib 25, again | 75025 | 0 times |
The second call is answered from the table. The first one is as slow as fib 25.
fib, the two recursive calls are calls of fib, not of mfib. The table sees only the calls that we make.memo_rec: the function receives the function to calllet fib' self n =
if n < 2 then n
else self (n - 1) + self (n - 2)
fib' does not call itself: it has no rec. It calls self, which it receives.
memo_rec fib' 25 = 75025 the body ran 26 times
OCamllet memo_rec f =
let table = Hashtbl.create 16 in
let rec g x =
match Hashtbl.find_opt table x with
| Some y -> y
| None ->
let y = f g x in
Hashtbl.add table x y;
y
in
g
memo_rec hands g, the function with the table, to f as its self. Every call goes through the table.| its type | order | ||
|---|---|---|---|
fib | int -> int | 1 | its argument is not a function |
memo | ('a -> 'b) -> ('a -> 'b) | 2 | its argument is a function |
fib' | (int -> int) -> (int -> int) | 2 | |
memo_rec | (('a -> 'b) -> ('a -> 'b)) -> ('a -> 'b) | 3 | its argument is a function whose argument is a function |
lazy), a list for each position (fibs), a table for each argument (memo).1. Given memo, write delay and force of the slide “lazy, made by hand” with it, and count the ticks.
2. Given memo_rec and the numbers of Pascal's triangle,
let rec choose (n, k) =
if k = 0 || k = n then 1
else choose (n - 1, k - 1) + choose (n - 1, k)
write choose', which receives the function to call, and count how many times each body runs for (24, 12).
| result | the body ran | |
|---|---|---|
choose (24, 12) | 2 704 156 | 5 408 311 times |
memo_rec choose' (24, 12) | 2 704 156 | 168 times |