Magic Scroll

Today we're publishing some runes form ancient and sacred Magic Scroll to meditate and enjoy, as an answer to the forces of the dark side...)))

;; Definition of CONS/CAR/CDR in Lambda Calculus.

(define (cons a d)
  (lambda (m)
    (m a d)))             ; accidental emergence of Truth

(define (car p)           ; CAR - Content of the Address Part of the Register
  (p (lambda (a d) a)))   ; A - Address part

(define (cdr p)           ; CDR - Content of the Decrement Part of the Register
  (p (lambda (a d) d)))   ; D - Decrement part

;; the explanation of Magic:
;;
;; define a procedure of two arguments in the global environment, called CONS,
;; which returns a procedure that accepts a procedure-of-two-arguments as its
;; argument and applies that procedure to the values of its formal parameters
;; stored in a frame that extends the global environment.
;;
;; This means - give me a procedure which knows what to do with my parameters.
;;
;; So, CAR invokes CONS with the argument which is a procedure that returns
;; the first of the two given arguments.
;; CDR invokes CONS with an argument that is a procedure which returns the
;; second of the two given arguments.

;; a trace
(car (cons (35 47)))
(car (lambda (m) (m 35 47)))                ; a cons object is a procedure
((lambda (m) (m 35 47)) (lambda (a d) a))   ; m is a procedure of two arguments
((lambda (a d) a) 35 47)                    ; application
35

;; encapsulating mutation

(define (cons a d)
  (lambda (m)
    (m a d
       (lambda (v) (set! a v))
       (lambda (v) (set! d v)))))

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

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

(define (set-car! p v)
  (p (lambda (a d sa sd) (sa v))))

(define (set-cdr! p v)
  (p (lambda (a d sa sd) (sd v))))

;; Happy Happy, Joy Joy!

Comments

No comments.