在Clojure中将关键字应用于映射与映射至关键字

Say I have a map {:x 1}.

I noticed that I can lookup :x either by applying it to the map:

(:x {:x 1})
;=> 1

或通过将地图应用于关键字:

({:x 1} :x)
;=> 1

两种形式有什么区别?

评论
  • 哼小曲
    哼小曲 回复

    Both maps and keywords implement IFn and therefor can be used as functions. The function they implement is get. So it basically always translates to (get map key default).

    因此,有一些自己可以弥补的经验法则;要考虑的一些事情:

    • if you have keywords in maps, using the keyword is the most common thing you will see in codebases
    • if your key is not a keyword or no function (e.g. strings), you are usually better off applying the map as function (e.g. ({"a" 1} "a"))
    • whenever you are not sure if the one thing you have (the key or the map) is nil, you are better off using the thing that know for sure is not null (or else you get an exception) (e.g. (nil {:a 1}) fails, but ({:a 1} nil) works); if you are unsure about both: use get