Typeclasses in common lisp

I am wondering if there is a way to emulate Haskell typeclasses in Common Lisp.

Common functions allow overloading , and types can be defined using deftype (which can be defined, for example, by membership in some list of instances).

But I can not dispatch for type. Is there a way to make a class a subclass (and a subtype) of some other class after it is defined (for example, make the class cons subclass of the sequence class without overriding cons )?

Thanks.

+5
source share
2 answers

Haskell type classes are a means of statically looking for implementations of "interfaces" in the form of dictionaries (similar to how vtables, for example, C ++ are used, but (almost) completely static, unlike C ++, which does dynamic dispatch at runtime), Common Lisp is, however, a dynamically typed language, so such a search does not make sense. However, you can implement your own approach to implementing "class instances" (instances) at run time - a design that is not as difficult to imagine in a language as expressive as Common Lisp.

PS Python Zope has an adaptation mechanism with very similar characteristics if you want to reference an existing solution in dynamic configuration.

+2
source

You cannot change the class hierarchy as you imagine it, but you can achieve almost the same effect.

Suppose your definition of a sequence is that it has a method for the sequence-length function.

 (defclass sequence ...) (defmethod sequence-length ((s sequence)) ...) 

Then you can easily extend your sequence-length method to the end:

 (defmethod sequence-length ((s cons)) (length s)) 

Has this class created 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 this is not very useful.

-1
source

All Articles