3 ms·
Multiple or predicate dispatch object systems take the view that objects are structs without methods in them. Methods are just open conditionals: by defining a
by jules 17y ago
Multiple or predicate dispatch object systems take the view that objects are structs without methods in them. Methods are just open conditionals: by defining a new method implementation you add a clause to the conditional.
e.g.
type Animal
type Lion < Animal
type Elephant < Animal
type Giraffe < Animal
method encounter(Animal, Animal)
def encounter(Lion a, Giraffe b):
// eat it
def encounter(Lion a, Lion b):
// fight
Is equivalent to:
type Animal
type Lion < Animal
type Elephant < Animal
type Giraffe < Animal
def encounter(Animal a, Animal b):
if(a is Lion && b is Giraffe):
// eat it
else if(a is Lion && b is Lion):
// fight
else:
raise NoApplicableMethodError
Languages with predicate dispatch usually allow you to define your own predicate classes:
def Prime(n): // primality testing algorithm here
def Foo(Prime n): ...
Or:
type Rectangle height width
def Square(Rectangle r): height(r) == width(r)
def Something(Square x): ...
def Something(Rectangle x): ...
And they allow you to add predicates to methods themselves:
def encounter(Lion a, Giraffe b) when isHungry(a): eat
def encounter(Lion a, Giraffe b) when !isHungry(a): walk away
This is much more powerful and simpler than message passing, IMO.
It's closely related to pattern matching in languages like Haskell, but that's usually not allowed to span multiple modules or files. And algebraic data types are closed, making it much less useful.
- eru 17y agoYes. There's also the possibilities to have open data types in Haskell. Also type classes, and being able to add instances for any type are closely related to your examples.
- jules 16y agoThat's interesting. I've read a paper about it, but I don't remember exactly. Is it implemented in GHC? Type classes are more powerful in some ways, but much less powerful in other ways. There is some overlap, but type classes dispatch only on the compile time type whereas this dispatches on run time predicates.
- eru 16y agoI agree. About more powerful: The static approach allows you to dispatch not only on argument types, but also on return type. A quick search reveals that there is some support for open data types in GHC, but I am not sure if it's more than an experimental feature.