Data as Procedures

I was watching lecture 2b of the SICP lectures and it shows an implementation of cons, car and cdr in Scheme as procedures. So I thought I’d write the equivalent in Common Lisp to test my understanding:

(defun my-cons (a b)
  #'(lambda (c)
      (cond ((= c 0) a)
            ((= c 1) b))))

(defun my-car (x) (funcall x 0))

(defun my-cdr (x) (funcall x 1))

(print (my-car (my-cons 'gold 'silver)))
(print (my-cdr (my-cons 'everything 'nothing)))

Output is:

$ clisp pairs.lisp

GOLD
NOTHING

Crazy. “Constructed out of thin air”, as Abelson says.

The scheme implementation is definitely nicer. See What Is Meant by Data? Scheme has only one namespace so there’s no need for the #' and funcall clutter.

2 Replies to “Data as Procedures”

  1. http://en.wikipedia.org/wiki/Lambda_calculus also has implementations of boolean and ordinal datatypes in terms of functions.

  2. There’s an even prettier version of this in my followup post at http://bluebones.net/2006/03/data-as-procedures-with-no-data/ which comes from Alonzo Church’s original Lambda Calculus, by way of Scheme.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.