Lecture 011

Continuation: all the stuff I will do later. (stack)

Adding

add: int -> int -> (int -> 'a) -> 'a)
fun add x y k = k (x+y)
fun mult x y k = k (x*y)

continuation passing style () continuation passing transformation: flip code inside out

(* (2+3)*4 *)
add 2 3 (fn r => mult r 4 (fun r' => r'))

Mult List

fun multList [] = 1
  | multList (x::xs) = x * multList xs

Make it tail recursive

fun tMultList ([], acc) = acc
  | tMultList (x::xs, acc) = tMultList(xs, x+acc)
fun multList' L = tMultList (L, 1)

Tail Recursive and with continuation, but not much faster, because there is still allocation of function

fun cmultList [] k = k 1
  | cmultList (x::xs) k = cmultList xs (fn y => k (x * y))
fun multlist'' L = cmultlist L (fun y -> y)

Optimize for 0 in multiplication: we can say for sure the result is always 0 if one of the input is 0.

(*
REQUIRES: k total, k 0 = 0
ENSURES cmultlist L k ~= k (multlist L)
*)
fun cmultList' [] k = k 1
  | cmultList' (x::xs) k =
  if x <> 0 then cmultList' xs (fn y => k (x * y)) else 0

In order traversal match of Tree

(*prefix: int tree -> int list -> (int list -> bool) -> bool
REUIQRES: k total
ENSURES: prefix T L k => true iff L = L1 @ L2 (for some L1, L2) such that inorder (T, []) ~= L1 and k L2 ~= true

*)
fun prefix Empty L k = k L
  | prefix (Node (l, x, r)) L k =
    prefix l L (fn [] => false
                 | y :: ys => x = y andalso prefix r ys k)

fun treematch' T L = prefix T L (fn [] => true | _ => false_)

a style like handling exception

(* search: ('a -> bool) -> 'a tree -> ('a -> 'b) -> (unit -> 'b ) -> 'b *)
fun search p Empty sk fk = fk ()
  | search p (Node(l, x, r)) sk fk =
  if p(x) then sk x
  else search p l sk (fn () => search p r sk fk)

so that you can do

search (fn n => n mod 2 = 0) T SOME (fn () => NONE)
search (fn n => n mod 2 = 0) T Int.toString (fn () => "NONE")
search (fn n => n mod 2 = 0) T (fn x => x) (fn () => 0)

CPS

CPS may and maynot

CPS may and maynot

fun find x = fn () => x;
val find = fn : 'a -> unit -> 'a
fun find x = x ();
val find = fn : (unit -> 'a) -> 'a

Table of Content