[Haskell-cafe] run-time type testing in haskell?

Eric eeoam at ukfsn.org
Sat Apr 28 09:33:02 EDT 2007


Robin Green wrote:
>
> In object-oriented languages you can achieve the same effect by
> defining a method on each type which has different behaviour depending
> on the type.
>
> In Haskell you can achieve much the same effect by defining methods in
> typeclasses and then defining instances for types. It's quite
> analogous. This is the recommended way of doing it in Haskell.
>   
I thought about that. But consider the following scenario. We have a 
Dispatcher and a Handler. The Dispatcher sends messages to Handlers. 
There are two ways we could implement this in an OOP language

(0) Have each type of message be a method on a Handler type class. The 
problem here is that to dispatch new message types we would have to 
recompile the Dispatcher.

(1) Have Handlers implement a method handle(m: Msg). To add new types of 
message, we declare message types which extend Msg. The Handler then 
uses runtime type testing to decide how to deal with each message. The 
advantage of this design is that we can add new Handler and new Msg 
types without recompiling the Dispatcher.

Type classes allow us to adopt approach (0) in Haskell, but don't seem 
to allow approach (1)....

E.



More information about the Haskell-Cafe mailing list