Multimethods Continued

My throw-away quip about multimethods drew more attention than I expected, even sparking a discussion on Twitter among people who really know about these kind of things -- implementors of dynamically typed languages, for example.

The main response I received was, quite reasonably, "Where's the evidence?".

By multimethod I meant any function where the behaviour depends on the type of more than one parameter. In object-oriented languages with single-dispatch, I count the receiver as one of those parameters. (This is made explicit in some languages, including Python and Lua.) Perhaps the term "generic function" would have been more precise.

Python

You can find examples in the standard library. For example, the add_argument method of the optparse.OptionParser is documented as:

add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)

That is, you can either pass an Option instance or one or more strings followed by keyword arguments.

The implementation begins with a conditional on the type of the first argument:

def add_option(self, *args, **kwargs):
    if type(args[0]) in types.StringTypes:
        option = self.option_class(*args, **kwargs)
    elif len(args) == 1 and not kwargs:
        option = args[0]
        if not isinstance(option, Option):
            raise TypeError, "not an Option instance: %r" % option
    else:
        raise TypeError, "invalid arguments"
    ...

The Python Package Index contains several implementations of multimethods. Searching for "generic functions" unearths even more. That's despite the there being an implementation of generic functions in the Python standard library, although, to be fair, it's hidden in the setuptools implementation and only dispatches on the type of the first parameter. PEP443 has has promoted this to the functools module in Python 3.

JavaScript

JavaScript libraries seem to type-switch on method parameters even more often than Python libraries. For example, jQuery's the global jQuery function (also aliased to $) can be passed many different type of parameter. Likewise for Prototype's global $ function. Like Python, JavaScript has several implementations of generic functions to choose between including Bilby, Joose, and Multimethod.

Ruby

Lua

Codea examples...

Tcl

Tcl has several object models.

Copyright © Nat Pryce. Posted . Share it.