Reputation: 4298
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.
Upvotes: 8
Views: 1019
Reputation: 5651
You cannot modify the class hierarchy in the way you envision, but you can achieve pretty much the same effect.
Suppose that your definition of a sequence
is that it has a method for the function sequence-length
.
(defclass sequence ...)
(defmethod sequence-length ((s sequence)) ...)
Then you can easily extend your sequence-length
method to conses:
(defmethod sequence-length ((s cons))
(length s))
Did that create a new class that includes cons
? Not really. You can express the type of things that have a sequence-length
method by saying (or sequence cons)
, but that's not really useful.
Upvotes: -1
Reputation: 38217
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.
Upvotes: 2