-
Hello, so my talk is going to be on multiple dispatch.
-
First for starters what is method dispatch?
-
If you have a polymorphic method
-
that mean if you have multiple implementations
-
and we'll soon see an example to make it clear what I mean
-
if you have those multiple implementations, the dispatch determines
-
which of those implementations will be called when you
-
invoke the method.
-
JavaScript has simple dispatch, so a single value is used for dispatch
-
we will then look at something new
-
and that is called multiple dispatch.
-
You can either dispatch via an object or
-
via a function. And if you dispatch via an
-
object this is what it looks like.
-
You have a so-called polymorphic method
-
and the type of jane determines which of the two functions
-
will be called if you make that method call up here.
-
So it depends on whether jane is a person or an employee
-
If on the other hand you have a generic function
-
then things work differently
-
jane is now just a normal argument and
-
the function internally checks the type of the argument
-
and then depending on the type of the argument
-
chooses between two different implementations.
-
The same principle can be used if you have more than one parameter
-
and naturally you then have to check the type of each
-
of those two parameters.
-
So if you implemented multiple dispatch as a library in JavaScript
-
this is what it would look like.
-
You would first create a generic function that's called plus
-
then you would add two methods
-
and finally you would invoke it as you would with any other function
-
and then the types of the parameters
-
determine which of the two implementations are invoked when you make the call
-
as you can see it's like a table that maps function types
-
or parameters types to methods.
-
What are the benefits? Why do you do that?
-
What's good about it?
-
So what's actually happens is
-
you get more symmetry
-
Normally, the implicit parameter "this" is more powerful
-
than the other explicit parameters when you have
-
single dispatch like in JavaScript
-
So that's one of the properties of multiple dispatch
-
And then functions also become object-oriented
-
they become aware of the type hierachy of objects
-
The benefits are that whenever you have a polymorphic algorithm
-
that applies to several objects, then you can put that into a generic function
-
and here you have the generic function foo
-
it works with three objects and then it's obvious that foo
-
doesn't belong to a single object
-
it belongs to all of the objects at the same time.
-
So generic functions allow you to do that
-
and you have the visitor pattern for
-
single dispatch languages and that is actually just
-
a generic function implemented as an object
-
an you use single dispatch in the host to trigger the right visitor method
-
and languages with multiple dispatch include
-
Common Lisp, Haskell, R, Groovy, Clojure and C#
-
That's it, thank you!