Skip to content

Instantly share code, notes, and snippets.

@ramirez7
Created December 27, 2013 23:42
Show Gist options
  • Save ramirez7/8154170 to your computer and use it in GitHub Desktop.
Save ramirez7/8154170 to your computer and use it in GitHub Desktop.
Visualization of continuation passing style using map as an example.
;; Non-tail recursive map
(define map
(lambda (f ls)
(if (null? ls)
'()
(cons (f (car ls)) (map f (cdr ls))))))
;; > (map add1 '(1 2 3))
;; (2 3 4)
;; Tail recursive map in continuation-passing style
(define map-cps
(lambda (f ls k)
(if (null? ls)
(k '())
(map-cps f (cdr ls) (lambda (d)
(k (cons (f (car ls)) d)))))))
;; Empty continuation. Just returns the value passed to it
(define empty-k
(lambda (v) v))
;; > (map-cps add1 '(1 2 3) empty-k)
;; (2 3 4)
;; Tail recursive map in cps with quoted continuations instead of
;; procedures so we can see the Scheme in the final continuation
(define map-cps-show
(lambda (f ls k)
(if (null? ls)
(begin
(printf "----- Continuation: -----\n")
(pretty-print k)
(printf "----- Result: -----\n")
((eval k) '()))
(map-cps-show f (cdr ls)
`(lambda (d)
(,k (cons ,(f (car ls)) d)))))))
;; quoted empty continuation
(define empty-k-show
'(lambda (v) v))
;; > (map-cps-show add1 '(1 2 3) empty-k-show)
;; ----- Continuation: -----
;; (lambda (d)
;; ((lambda (d)
;; ((lambda (d) ((lambda (v) v) (cons 2 d))) (cons 3 d)))
;; (cons 4 d)))
;; ----- Result: -----
;; (2 3 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment