代码改变世界

转:implementing cons/car/cdr without explicit storage

2014-03-09 19:06  youxin  阅读(270)  评论(0编辑  收藏  举报

I know this is old wine but it’s just too cool! It elegantly demonstrates closure and higher-order functions in a dozen lines, yet retains the robustness. The “intuitive” idea of storage is totally absent, replaced by the “environment” reserved by the interpreter. The first time I saw this is in the SICP videos.

(define (cons a d)
  (lambda (op) (op a d)))

(define (car p)
  (p (lambda (a d) a)))

(define (cdr p)
  (p (lambda (a d) d)))

> (car2 (cons2 1 2))
1
> (cdr2 (cons2 1 2))
2
>转自:http://pro.harrypan.net/wp/?p=835