[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [NOISE] Curly braces [was Re: Curl]




Okay, since you asked, here is another goodie. Dan asked about implementing
classes as a library. Well that's what mzscheme does. The file class.ss
implements a *syntactic* library for classes, plus the supportive run-time
system. But, you won't be able to tell that this is user-defined
syntax. The errors are reported at the level of the surface syntax -- as if
this lib had been built in. 

-- Matthias

; drscheme: module language 

(module sample mzscheme
        (require (lib "class.ss")
                 (lib "etc.ss"))

        (define Account% 
          (class* object% ()
            ; Declare public methods:
            (public add subtract balance)
            
            (define amount 0)        ; A private field    
            
            ; Method implementations:
            ; -----------------------
            
            ; Symbol Symbol (Number Number -> Number) -> (Number -> Account%)
            (define (make-delta name type op)
              (local ((define (add delta)
                        (if (>= delta 0)
                            (set! amount (op amount delta))
                            (error name "~a must be >= 0, given: " type delta))
                        this))
                add))
            
            ; -> Number
            (define (balance) amount)
            
            ; Number -> Account%
            (define (add delta) [(make-delta 'add 'deposit +) delta])
            
            ; Number -> Account%  
            (define (subtract delta) [(make-delta 'subtract 'withdrawal -) delta])
            
            ; Call superclass initializer:
            (super-instantiate ())))
        
        ;; Test: 
        (define an-account (make-object Account%))
        
        (define result 
          (= 25 
             (send
              (send 
               (send an-account 
                     add 50)
               subtract 25)
              balance)))
        )