跳到正文

个人记录

CPSer

litjohn约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年1月2日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

这里记录最终版的完整代码:

racket
#lang racket

(define (atom? x) (not (pair? x)))

(define (wrap k exp)
  (if (eq? k 'identity)
    exp
    (list k exp)))

(define keywords '(lambda))

(define (is-app-exp? exp)
  (not (or (atom? exp) (member (car exp) keywords))))

(define (cps1 exp k env)
    (match exp
        [`(lambda ,bind ,body)
            (let ([res (let ([c (gensym 'k)])
                            `(lambda ,(append bind (list c)) ,(cps1 body c '())))])

                (wrap k res))]

        [`(,exp)
            (let ([c1 (gensym 'v)])
                (if (is-app-exp? exp)
                    (cps1 exp `(lambda (,c1) ,(reverse (cons k (cons c1 env)))) '())
                    (reverse (cons k (cons (cps1 exp 'identity '()) env)))))]

        [`(,exp1 . ,rest) (not (null? rest))
            (let ([c1 (gensym 'v)])
                (if (is-app-exp? exp1)
                    (cps1 exp1 `(lambda (,c1) ,(cps1 rest k (cons c1 env))) '())
                    (cps1 rest k (cons (cps1 exp1 'identity '()) env))))]

        [x (atom? x) (wrap k x)]))

(define (cps exp) (cps1 exp 'ctx0 '()))
原文