I tried to use it, but couldnt find a way to discern it from ordinary function.
(define (cons x y)
(define (dispatch m)
(cond ((= m 0) x)
((= m 1) y)
(else (error "Argument not 0 or 1 -- CONS" m))))
dispatch)
(define (car z) (z 0))
(define (cdr z) (z 1))
Name:
Anonymous2010-12-29 6:29
Read SICP.
Name:
Anonymous2010-12-29 6:33
(define (make-ordinary-function fn)
(define (dispatch m . args)
(cond ((= m 'type) 'function)
((= m 'funcall) (apply fn args))
(else (error "Invalid funcall"))))
dispatch)
>>1
It's not different from an ordinary function in your example. It's just an example that shows that a cons could be implemented as a closure. What exactly is a cons? Something that holds a pair of two objects somehow. The internals are irrelevant for that example. What's relevant is that you can access a cons through an interface (car/cdr at least), which is what you do up there. In a real implementation, cons is a real data structure, and you would be able to define all kinds of data structures and so on, for efficiency reasons, but if not for that, you could just use closures for most data structures and it would work just fine.
>>1
Here some code I wrote in my free time, it implements a simple message passing style oop. You can even implement inheritance with a little of effort, by using the super class' 'mmap method.
(define-syntax λm
(λ (stx)
(syntax-case stx ()
((λm args v ...)
(with-syntax ((self (datum->syntax #'λm 'self)))
#'(λ (self . args) v ...)))
((λm (a ...) v ...)
(with-syntax ((self (datum->syntax #'λm 'self)))
#'(λ (self a ...) v ...))))))
(define mmap
(λ (m t b)
(cond ((null? m) (list (cons t b)))
((eq? t (caar m)) (cons (cons t b) (cdr m)))
(else (cons (car m) (mmap (cdr m) t b))))))
(define make-dispatcher
(λ (m)
(define dispatcher
(λ (z . a)
(cond ((eq? z 'mmap) m)
((eq? z 'set-method) (set! m (apply mmap (cons m a))))
((assq z m) => (λ (h) (apply (cdr h) (cons dispatcher a))))
((eq? z 'get-class) "UNKNOWN")
((eq? z 'to-string) (symbol->string (dispatcher 'get-class)))
(else (error (format "Undefined method \"~a\" for class \"~a\"" z (dispatcher 'get-class)))))))
dispatcher))