dispatching to same function name based on argument type

M

metaperl

In this video -
http://video.google.com/videoplay?d...=14&start=0&num=10&so=0&type=search&plindex=0

Peter Seibel says that Lisp generic functions give Lisp an edge in
"double dispatch" or even higher degrees of dispatch. I.e., when you
must decide which function to run based on the types of n or more
things.

The example he gave was displaying one of { Book, CD, DVD } to
any of { Text , Graphics }

but can't you simply write a bunch of static functions for each case?
Ie:

static void display(Book b, TextDisplay t);
static void display(Book b, GraphicDisplay t);

and so on?
 
P

Patricia Shanahan

metaperl said:
In this video -
http://video.google.com/videoplay?d...=14&start=0&num=10&so=0&type=search&plindex=0

Peter Seibel says that Lisp generic functions give Lisp an edge in
"double dispatch" or even higher degrees of dispatch. I.e., when you
must decide which function to run based on the types of n or more
things.

The example he gave was displaying one of { Book, CD, DVD } to
any of { Text , Graphics }

but can't you simply write a bunch of static functions for each case?
Ie:

static void display(Book b, TextDisplay t);
static void display(Book b, GraphicDisplay t);

and so on?

You can, but the class containing the static methods would have N*M
methods, where N is the number of media and M is the number of displays.
It would have to be updated for addition of either a new medium or a new
display type.

Ideally, one would implement e.g. paper tape input by adding a class
PaperTape, implementing the same interface as Book, CD, and DVD, and
that would be the end of the matter.

Patricia
 
E

Eric Sosman

Patricia Shanahan wrote On 08/24/07 11:06,:
You can, but the class containing the static methods would have N*M
methods, where N is the number of media and M is the number of displays.
It would have to be updated for addition of either a new medium or a new
display type.

Ideally, one would implement e.g. paper tape input by adding a class
PaperTape, implementing the same interface as Book, CD, and DVD, and
that would be the end of the matter.

Also, note that Java's determination of which method
to call depends on the compile-time types of the arguments,
not their run-time types. If all these things are subclasses
of Media and Display, as appropriate, then

Media m = new Book();
Display d = new TextDisplay();
display(m, d);

.... will *not* call the first of your static functions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top