Skip to content

Instantly share code, notes, and snippets.

@kmicinski
Created October 7, 2025 23:21
Show Gist options
  • Select an option

  • Save kmicinski/5116f73a19d8b91a3abb132a781f1c29 to your computer and use it in GitHub Desktop.

Select an option

Save kmicinski/5116f73a19d8b91a3abb132a781f1c29 to your computer and use it in GitHub Desktop.
Code from class: 10/07 (CPS, etc.)
#lang racket
(define (atom? a)
(match a
[(? integer? i) #t]
[(? symbol? x) #t]
[_ #f]))
(define (anf-transform e)
;; e is the expression to be converted
;; k is the continuation (accepts an atom)
(define (c-e e k)
(match e
[(? atom? a) (k a)]
[`(- ,e)
(c-e e
;; continuation, c-e calls me back with a normalized version
;; of e
(lambda (atom)
(define x (gensym)) ;; give me a fresh symbol
`(let ([,x (- ,atom)]) ,(k x))))]
['(read)
(define x (gensym))
`(let ([,x (read)]) ,(k x))]
[`(let ([,x ,e0]) ,e-b)
(c-e e0 (lambda (a0)
(define x (gensym))
`(let ([,x ,a0]) 'todo)))]
[`(+ ,e0 ,e1)
(c-e e0 (lambda (a0)
(c-e e1 (lambda (a1)
;; I'm done with convering e0 (converted to a0)
;; and converting e1 (converted to a1)
(define x (gensym))
`(let ([,x (+ ,a0 ,a1)]) ,(k x))))))]))
(c-e e (lambda (x) x)))
;(pretty-print (anf-transform '(- x)))
;(pretty-print (anf-transform '(- (- (- x)))))
;(anf-transform 'x)
(pretty-print (anf-transform '(+ (read) (+ y z))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment