开发者

Defining Clojure multimethods

I have 开发者_如何学Cthe following in one namespace say shapes:

(derive ::rect ::shape)
(derive ::square ::rect)

Now executing the following in the shapes namespace:

(isa? ::square ::shape)

returns true. But when I execute the following in a namespace where I actually implement multimethods for drawing,

(isa? ::square ::shape)

it returns false. So even though I have the correct multimethod dispatch functions in place I get an error that says "no dispatch function found".

Am I missing something? Implementing all types of shapes in one giant namespace seems pointless to me.


Turns out, :: uses the current namespace so in order to use types from other namespaces you need to use fully qualified names such as :shapes/square.


You are correct, in your self-answer, that the :: operator locates something in the current namespace.

One interesting point is that the keywords can be namespaced in any namespace you like, even one which isn't declared in any file. So if your namespace tree is complicated, and you prefer :geometry/square, :geometry/circle, and the like, you can just use that.

Also, don't forget that derive, underive (don't use underive right now), isa? and related functions all let you use an independent hierarchy if you want. See When and how should independent hierarchies be used in clojure?


You can use :: also with namespace aliases.

(ns some.other.package
  (:require [some.terr.ibly.long.package.name :as short]))

Now: ::short/abc will refer be the same as :some.terr.ibly.long.package.name/abc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜