[racket] Applicable objects

From: David Van Horn (dvanhorn at ccs.neu.edu)
Date: Tue Dec 14 11:17:48 EST 2010

I don't know boo about Scala, but I was watching this intro talk by Dean 
Wampler, who wrote the O'Reilly book on Scala:


I learned that every Scala object that defines an apply method can be 
used as a function.  Cute.  It's nice to see a language emphasize the 
symmetry between objects and functions.

So then I took a few minutes to code up the idea in Racket:

#lang racket
(require test-engine/racket-tests)

(define applicable<%>
   (interface* ()
                 (λ (obj x) (send obj apply x))])

(define fun%
   (class* object% (applicable<%>)
     (init-field f)
     (define/public (apply x)
       (f x))

(define deriv
   (new (class* object% (applicable<%>)
          (define d #e0.001)
          (define/public (apply g)
            (new fun% [f (λ (x)
                           (/ (- (g (+ x d))
                                 (g (- x d)))
                              (* 2 d)))]))

(define sqr (new fun% [f (λ (x) (* x x))]))

(check-expect (send sqr apply 4) 16)
(check-expect (sqr 4) 16)

(check-expect ((send deriv apply sqr) 4) 8)
(check-expect ((deriv sqr) 4) 8)


It's nicer to see a language that enables creating languages that 
emphasize the symmetry between objects and functions.

Thanks PLT.


Posted on the users mailing list.