我正在学习 CLOS 中的泛型函数。
由于我在教科书和网上找到的示例类型,我变得非常困惑。这些示例总是使用有多个分派的事实。根据参数类型,执行不同的计算。但是,为什么这些论点本身从未在示例中使用过?
来自维基百科的示例代码
; declare the common argument structure prototype
(defgeneric f (x y))
; define an implementation for (f integer t), where t matches all types
(defmethod f ((x integer) y) 1)
(f 1 2.0) => 1
; define an implementation for (f integer real)
(defmethod f ((x integer) (y real)) 2)
(f 1 2.0) => 2 ; dispatch changed at runtime
在上面的示例中,您可以看到方法本身从未实际使用x
ory
变量。所有这些示例从不使用变量是巧合吗?它们可以使用吗?
此外,它写在Wikipedia上:
方法与类分开定义,它们对类槽没有特殊的访问权限(例如“this”、“self”或“protected”)。
好的,所以方法没有“this”,因为它们不属于一个类。但是为什么泛型函数方法可以有一个接收器呢?接收器不是类似于类中的'this'吗?