Skip to content

Instantly share code, notes, and snippets.

@shhyou
Created June 12, 2013 14:38
Show Gist options
  • Save shhyou/5765867 to your computer and use it in GitHub Desktop.
Save shhyou/5765867 to your computer and use it in GitHub Desktop.
The Y combinator for applicative-order evaluation and its CPS-transformed version
(define Y
(lambda (f)
(let [(A (lambda (x) (f (lambda (y) ((x x) y)))))]
(A A))))
(define (factF self)
(lambda (n)
(if (= n 0)
1
(* n (self (- n 1))))))
(define fact (Y factF))
(display (fact 5)) (newline)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (Y-cps f k-f)
(let [(A (lambda (x k-x)
(f (lambda (y k-y) (x x (lambda (v-xx) (v-xx y k-y)))) k-x)))]
(A A k-f)))
(define (factF-cps self k)
(k (lambda (n k-n)
(if (= n 0)
(k-n 1)
(self (- n 1) (lambda (res) (k-n (* n res))))))))
(define (fact-cps k) (Y-cps factF-cps k))
(fact-cps (lambda (f) (f 5 display))) (newline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment