Emma Boudreau
2 min readApr 3, 2021

--

Dispatching is a way that you can handle multiple types with different arithmetic under one consistent call. Let us consider that you have a function that subtracts one from whatever you put into it.

def minus1(x):
return(x - 1)

If we wanted to pass a list through this function, we would get an error in return. This is because we cannot subtract a list by an integer. However, if we were to pass an integer this function would work fine. It would be pretty strange to create multiple calls for this purpose, and have two functions like this:

def minus1(x):
return(x - 1)

and

def minus1_list(x):
[a - 1 for a in x]

So using multiple dispatch, we could define the same function under the same name, but specify the kind of type we would like to use.

@minus1.register
def minus1(x : int):
return(x - 1)
@minus1.register
def minus1(x : list):
[a - 1 for a in x]

The Julia language actually takes this concept into outer space by using it as a paradigm. I definitely recommend the usage to any programmer, because it is a really great way to program that keeps the language out of the way of the relationship between functions and types. Of course, this is my opinion, but regardless I think most would at least find it interesting. The concept works off the grounds of something called parametric polymorphism, which is where these functions are applied as properties of types, or the type’s functions are applied as properties of the function in the Pythonic example. It was originally introduced into the ML language back in the day, and has really made a resurgence with high-level statistical languages. I hope this was helpful.

--

--

Emma Boudreau
Emma Boudreau

Written by Emma Boudreau

i am a computer nerd. I love art, programming, and hiking. https://github.com/emmaccode

No responses yet