[racket] Choosing what class to instantiate at runtime
Hi all,
I'd like to refactor and extend the code below, such that r is either
defined to be an instance of an item-representer% or a
multi-item-representer%, depending on whether param-a is a single item or a
list.
The solution that springs to mind is to choose which class to instantiate
with (if (list? param-a) ,,,) but then I'd have to state the parameter
lists twice.
It seems to me there's got to be a better way in Racket to do this. Thanks
in advance for any suggestions on how to proceed.
Cheers,
Kieron.
****
#lang racket
(define text-item "hello world")
(define text-item-list (list "alpha bravo" "charlie delta" "echo foxtrot"))
(define x%
(class object%
(super-new)
))
(define item-representer%
(class x%
(init param-a param-b param-c)
(super-new)
(field (item param-a))
(define/public (print)
(printf "item:~a~n" item))
))
(define multi-item-representer%
(class x%
(init param-a param-b param-c)
(super-new)
(field (item-list (map (lambda (item) (new item-representer% [param-a
item] [param-b param-b] [param-c param-c])) param-a)))
(define/public (print)
(printf "multi-item:~n")
(map (lambda (item) (send item print)) item-list)
)
))
(define r1 (new item-representer% [param-a text-item] [param-b 10] [param-c
"red"]))
(define r2 (new multi-item-representer% [param-a text-item-list] [param-b
20] [param-c "green"]))
(send r1 print)
(send r2 print)
;(define r (some-representer% [param-a x] [param-b 50] [param-c "yellow"]))
;(send r print)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20120625/fabdd685/attachment-0001.html>