简体   繁体   English

命名空间映射名称空间上的多方法分派

[英]Multimethod dispatch on namespaced map namespace

Is it possible to dispatch based on a namespaced map namespace ie #:<this-thing>{} ? 是否可以基于命名空间的地图命名空间(即#:<this-thing>{}进行调度? Without hacks like printing or inspecting key prefixes? 是否没有像打印或检查键前缀这样的hacks?

I consider the last one hacky because a key prefix can be overridden: 我认为最后一个是hacky,因为可以覆盖键前缀:

(:qux/bar #:qux{:bar :baz}); => :baz
(:foo/bar #:qux{:foo/bar :baz}); => :baz
(:qux/bar #:qux{:foo/bar :baz}); => nil

A map might contain all qualified keyword keys from a certain namespace, or it may contain a mix of unqualified keys or qualified keys from multiple namespaces. 映射可能包含某个命名空间中的所有合格关键字键,也可能包含不合格键或多个命名空间中合格键的混合。 Here's a function to get the set of all namespaces (as keywords) from qualified keyword keys in a map: 这是一个从映射中的合格关键字键获取所有名称空间(作为关键字)的集合的函数:

(defn key-namespaces
  "Returns set of all namespaces of keys in m."
  [m]
  (->> (keys m)
       (keep (comp keyword namespace))
       (set)))

Now you can use that as a dispatch-fn on a multimethod: 现在,您可以将其用作多方法上的dispatch-fn

(defmulti do-thing key-namespaces)
(defmethod do-thing #{:foo} [m] (prn m))
(do-thing #:foo{:bar 1})
;; #:foo{:bar 1}
(foo {:bar/bar 1})
;; no multimethod found exception

You could specify multiple namespace prefixes in that set, or you could use a different dispatch-fn based on your use case. 您可以在该集中指定多个名称空间前缀,也可以根据用例使用其他的dispatch-fn

This is not possible as this is just the visual representation of the map produced by writer . 这是不可能的,因为这仅仅是由所产生的图的视觉表示writer You would have to do the checks by yourself if all the keys in your map share the same namespace. 如果映射中的所有键共享相同的名称空间,则必须自己进行检查。 Also the last example won't be produced by the writer - it will emit namespaced map literal only when all the keys share the same namespace . 同样,最后一个示例不会由编写者生成-它仅在所有键共享同一命名空间时才会发出命名空间映射文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM