Common Lisp中的类型类 [英] Typeclasses in Common Lisp
问题描述
我想知道是否有方法模拟Common Lisp中的Haskell的 typeclasses
。
$ b
通用函数允许重载
,并且可以使用 deftype
(例如,可以通过成员身份来定义一些实例列表)。
但是我不能在一个类型上 dispatch
。有没有办法让一个类的子类(和一个子类型)在其定义之后(例如,使 cons
类成为 sequence
class,无需重新定义 cons
)?
谢谢。
在Haskell中类型类是静态查找字典形式的接口实现的手段(类似于例如C ++中的vtables (但几乎)完全静态地使用,而不像在运行时动态调度的C ++)。然而Common Lisp是一种动态类型语言,所以这样的查找将毫无意义。但是,您可以在运行时自行查找类型实现(实例) - 这种设计在语言上不像Common Lisp那样难以想象。
如果您想要在动态设置中引用现有解决方案,Python的Zope具有非常类似特征的自适应机制。
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.
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.
这篇关于Common Lisp中的类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!