Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeclasses in Common Lisp

I'm wondering if there's a way to emulate Haskell's typeclasses in Common Lisp.

Generic functions allow overloading, and it's possible to define types using deftype(which could be defined by membership to some list of instances, for example).

But I can't dispatch on a type. Is there a way to make a class a subclass(and a subtype) of some other class after its definition(e.g. making the cons class a subclass of a sequence class, without redefining cons)?

Thanks.

like image 779
Charles Langlois Avatar asked Jun 04 '15 07:06

Charles Langlois


People also ask

What is a method in Common Lisp?

In Common Lisp, methods are instances of generic functions, which can dispatch on not just the first argument, but every argument. This makes functions, rather than classes, the prime mover. We define a generic function with defgeneric:

What makes Lisp so special?

Part of what makes Lisp distinctive is that it is designed to evolve. As new abstractions become popular (object-oriented programming, for example), it always turns out to be easy to implement them in Lisp. Like DNA, such a language does not go out of style.

What is object orientation in Common Lisp?

Object Orientation In most OOP systems, methods belong to classes. In Common Lisp, methods are instances of generic functions, which can dispatch on not just the first argument, but every argument. This makes functions, rather than classes, the prime mover.

What is the Common Lisp rail scheduling system?

SISCOG’s Common Lisp rail scheduling system moves millions of passengers across Europe every day.


1 Answers

Type classes in Haskell are a means to statically look up implementations for "interfaces" in the form of dictionaries (similarly to how vtables in e.g. C++ are used but (almost) fully statically, unlike C++ which does dynamic dispatch at runtime). Common Lisp however is a dynamically typed language so such lookup would make no sense. However you can implement your own look up of "type class" implementations (instances) at runtime — a design not too hard to imagine in a language as expressive as Common Lisp.

P.S. Python's Zope has an adaption mechanism with very similar charactetistics, if you feel like referring to an existing solution in a dynamic setting.

like image 140
Erik Kaplun Avatar answered Oct 02 '22 01:10

Erik Kaplun