[racket] Best practices for classes

From: Alexander D. Knauth (alexander at knauth.org)
Date: Thu Oct 2 22:43:31 EDT 2014

I don’t know if you can do it with generic interfaces (as in racket/generic), 
but you can make classes whose instances have struct-type properties such as prop:procedure and prop:sequence
(using interfaces as in racket/class, not racket/generic)

#lang racket

(define proc<%>
  (interface* ()
              ([prop:procedure
                (lambda (this . args)
                  (send/apply this proc args))])
              proc))

(define proc%
  (class* object% (proc<%>)
    (super-new)
    (define/public (proc x)
      (displayln "this is the proc method of proc%")
      x)))

(define seq<%>
  (interface* ()
              ([prop:sequence
                (lambda (this)
                  (send this get-sequence))])
              get-sequence))

(define seq%
  (class* object% (seq<%>)
    (super-new)
    (define/public (get-sequence)
      (list 1 2 3))))

> (define p (new proc%))
> (p 1)
this is the proc method of proc%
1
> (define s (new seq%))
> (sequence-for-each displayln s)
1
2
3

On Oct 2, 2014, at 6:21 PM, Matthew Butterick <mb at mbtype.com> wrote:

> What's the best approach to:
> 
> + defining a class whose instances can be used as procedures?
> 
> (define ci (new proc-class%))
> (ci arg arg2 ... )
> 
> + ... whose instances can be used as lists (or at least support direct iteration?)
> 
> (define li (new listish-class%))
> (for-each displayln li)
> (map ci li)
> 
> My intuition is "implement a generic interface..." But then it gets hazy. 
> 
> 
> 
> 
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20141002/c559925a/attachment.html>

Posted on the users mailing list.