[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:

http://at.pscdn.net/008/00102/videoplatform/kv/100917scalaKV.html

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* ()
               ([prop:procedure
                 (λ (obj x) (send obj apply x))])
      apply))

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

(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)))]))
          (super-new))))


(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)

(test)

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

Thanks PLT.

David


Posted on the users mailing list.