Last active
May 3, 2019 09:04
-
-
Save suzusime/10e642e8352cc7358776800475e5fab3 to your computer and use it in GitHub Desktop.
継続渡し形式への変換例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* 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