Multimethods, generic functions

Well, I could try to explain without delving too deep into Lisp specifics. There is a risk that that devolves into a discussion about alternative ways of implementing the same thing, which of course is always possible. So I’d need to find cases that would be particularly elegant using multimethods.

Let’s take CLIM as an example. CLIM is a GUI framework for Common Lisp which heavily uses CLOS for extensibility. With CLIM, you can create visualiation functions for custom objects. In other words, you tell the system how an object should be displayed and all you have to do is to write this object to the output stream, and it will be displayed at the current cursor position.

The display function is a generic function, and you write methods on this function to customise how they are displayed. Here are the arguments to this function:

  • The object to be printed
  • The type of the object
  • The stream that the object should be written to
  • The view type the container belongs to

To implement a display method that is used every time an instance of a given class is to be displayed, all you have to do is to specialise on the object type.

The benefit to this approach, however, is that I can create extra methods that specialise on the stream type or the view. For example, I might to create a method that specialises on all integers when they are displayed in a certain panel. I would do this by specialising on object type integer as well as the specific view type for that panel.

I used integer as an example specifially to point out that these methods are not tied to a class. If I had to add these methods to the class itself, I couldn’t specialise on a Kotlin integer instance, since that class is not available to be modified. And even if I could, I’d have to put the code together with the integer implementation which is not really where it belongs.

If anyone is interested to see some of my code that actually uses this, and if you’re willing to read Lisp code, you can have a look at my Mastodon client: https://github.com/lokedhs/mastodon/blob/master/src/format.lisp. Look at uses of define-presentation-method which is a macro that expands to the specific method definition.

The book Practical Common Lisp gives a pretty good introduction to generic functions: Object Reorientation: Generic Functions