Hacker Newsnew | past | comments | ask | show | jobs | submitlogin



One of the links from this page mentions this: http://okmij.org/ftp/Scheme/oop-in-fp.txt, where the author presents a simple example of implementing an object using closures:

  (define (make-point-2D x y)
    (define (get-x) x)
    (define (get-y) y)
    (define (set-x! new-x) (set! x new-x))
    (define (set-y! new-y) (set! y new-y))
    (lambda (selector . args)     ; a dispatcher
        (case selector
          ((get-x) (apply get-x args))
          ((get-y) (apply get-y args))
          ((set-x!) (apply set-x! args))
          ((set-y!) (apply set-y! args))
          (else (error "don't understand " selector)))))
Which is curiously similar to the canonical object implementation of SICP in section 3.2:

  (define (make-account balance)
    (define (withdraw amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))
    (define (deposit amount)
      (set! balance (+ balance amount))
      balance)
    (define (dispatch m)
      (cond ((eq? m 'withdraw) withdraw)
            ((eq? m 'deposit) deposit)
            (else (error "Unknown request -- MAKE-ACCOUNT"
                         m))))
    dispatch)


Actually, Anton van Straaten said that. Classic.


A closure is an object that supports exactly one method: "apply". - Guy




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: