按关键字查找惯用clojure地图 [英] Idiomatic clojure map lookup by keyword

查看:87
本文介绍了按关键字查找惯用clojure地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个使用关键字作为键的clojure地图:

Say I have a clojure map that uses keywords as its keys:

(def my-car {:color "candy-apple red" :horsepower 450})



我知道我可以查找与使用关键字或地图作为函数,另一个作为其参数:

I know that I can look up the value associated with the keyword by either using the keyword or the map as a function and the other as its argument:

(my-car :color)
; => "candy-apple red"
(:color my-car)
; => "candy-apple red"

我意识到这两种表单在某些情况下可派上用场,

I realize that both forms can come in handy for certain situations, but is one of them considered more idiomatic for straightforward usage like shown above?

推荐答案

(:color my-car )是相当标准的。这有几个原因,我不会去所有的。但这里有一个例子。

(:color my-car) is fairly standard. There are a few reasons for this, and I won't go into all of them. But here's an example.

因为:color 是一个常数, my-car 不是,hotspot可以完全内联 color.invoke(m)的动态分派,它不能用 m.invoke颜色)(在某些Java伪代码中)。

Because :color is a constant, and my-car is not, hotspot can completely inline the dynamic dispatch of color.invoke(m), which it can't do with m.invoke(color) (in some java pseudo-code).

如果 my-car 有时是一个带有 color 字段而不是平面映射的记录:clojure编译器可以发出代码来检查hey,if my-car 是CarType的一个实例,然后只是返回 my-car.color ;否则执行所有的复杂,慢,hashmap查找。

That gets even better if my-car happens to sometimes be a record with a color field instead of a plain map: the clojure compiler can emit code to check "hey, if my-car is an instance of CarType, then just return my-car.color; otherwise do all the complicated, slow, hashmap lookup."

这篇关于按关键字查找惯用clojure地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆