(*
Examples of CPS (continuation passing style)
*)
(* straightforward recursion *)
let rec sum1 s =
match s with
[] -> 0
| x::xs -> x + sum1 xs
(* tail recursive *)
let sum2 s =
let rec sum' s a =
match s with
[] -> a
| x::xs -> sum' xs (a + x)
in
sum' s 0
(* using continuations *)
let sum3 s =
let rec sum' s k =
match s with
[] -> k 0
| x::xs -> sum' xs (fun a -> k (x + a))
in
sum' s (fun x -> x)