About archiving my SICP related stuff on GitHub

Well, I have done some exercises offered by the books Simply Scheme and the SICP for my own personal development and joy.

One interesting example is the representation of pairs as procedures. Instead of using a data structure we can use ordinary procedures to achieve the same, with identical semantics.

;;; Procedural representation of pairs
(define (cons x y)
  (define (dispatch m)
    (cond ((= m 0) x)
	  ((= m 1) y)
	  (else (error "Only 0 or 1 is allowed as argument -- CONS" m))))
  dispatch)

(define (car z)
  (z 0))

(define (cdr z)
  (z 1))

Another example

;;; Procedural representation of pairs
(define (cons x y)
  (lambda (m) (m x y)))

(define (car z)
  (z (lambda (p q) p)))

(define (cdr z)
  (z (lambda (p q) q)))

Or another example introducing mutation on top of that

(define (cons x y)
  (define (set-x! v) (set! x v))
  (define (set-y! v) (set! y v))
  (define (dispatch m)
    (cond ((eq? m 'car) x)
	  ((eq? m 'cdr) y)
	  ((eq? m 'set-car!) set-x!)
	  ((eq? m 'set-cdr!) set-y!)
	  (else (error "Undefined operation -- CONS" m))))
  dispatch)

(define (car z) (z 'car))

(define (cdr z) (z 'cdr))

(define (set-car! z new-value)
  ((z 'set-car!) new-value)
  z)

(define (set-cdr! z new-value)
  ((z 'set-cdr!) new-value)
  z)

To see more, please take a look at: SICP and Simply Scheme.

Related stuff:

About archiving my SICP related stuff on GitHub