Skip to content

Instantly share code, notes, and snippets.

@suzusime
Last active May 3, 2019 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suzusime/10e642e8352cc7358776800475e5fab3 to your computer and use it in GitHub Desktop.
Save suzusime/10e642e8352cc7358776800475e5fab3 to your computer and use it in GitHub Desktop.
継続渡し形式への変換例
(* Example of Continuation Passing Style *)
(* cf. http://practical-scheme.net/docs/cont-j.html *)
type tree =
Leaf
| Node of int * tree * tree
;;
let rec sum_nodes t =
match t with
| Leaf -> 0
| Node (i, l, r) ->
i + (sum_nodes l) + (sum_nodes r)
;;
let rec sum_nodes_cps t cont =
match t with
| Leaf -> (cont 0)
| Node (i, l, r) ->
sum_nodes_cps l (fun n ->
sum_nodes_cps r (fun m ->
cont (i + n + m)))
;;
let identity x = x;;
let t1 = Node(8, Node(4, Node(7, Leaf, Leaf), Leaf), Node(5, Leaf, Leaf));;
let r1 = sum_nodes t1;;
let r1_cps = sum_nodes_cps t1 identity;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment