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.
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:
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.
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.
SISCOG’s Common Lisp rail scheduling system moves millions of passengers across Europe every day.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With