为什么使用关键字或符号作为函数从地图中查找值工作? [英] Why does using keywords or symbols as functions to lookup values from maps work?

查看:164
本文介绍了为什么使用关键字或符号作为函数从地图中查找值工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Clojure的快乐,第4.3.1节 -

Quoting from Joy of Clojure, section 4.3.1--


因为关键字是自我评估并提供快速的等式检查,它们几乎总是在映射关键字的上下文中使用。使用关键字作为映射键的同样重要的原因是它们可以用作函数,以地图作为参数来执行值查找:

Because keywords are self-evaluating and provide fast equality checks, they're almost always used in the context of map keys. An equally important reason to use keywords as map keys is that they can be used as functions, taking a map as an argument, to perform value lookups:



(def population {:zombies 2700, :humans 9})
(:zombies population)
;=> 2700
(println (/ (:zombies population)
(:humans population))
"zombies per capita")
; 300 zombies per capita

这不是很明显。不知何故(:zombies population)必须转化为(get population:zombies)这是如何工作的?关键字求值为自身,而不是函数。读者是否注意到列表中的第一件事是关键字的情况,并添加get并将关键字移动到列表的末尾?

It is not apparent to me what is going on here. Somehow (:zombies population) has to get transformed into (get population :zombies), right? How exactly does this work? The keyword evaluates to itself, not to a function. Does the reader look out for cases where the first thing in a list is a keyword, and add get and move the keyword to the end of the list?

推荐答案

来自官方文档的引文:


关键字为具有可选第二个参数(默认值)的一个参数(地图)的invoke()实现IFn。例如(:mykey my-hash-map:none)表示与(get my-hash-map:mykey:none)相同。请参阅get。

Keywords implement IFn for invoke() of one argument (a map) with an optional second argument (a default value). For example (:mykey my-hash-map :none) means the same as (get my-hash-map :mykey :none). See get.

Clojure可以将关键字调用为函数,因为它实现了与函数相同的接口。同样的符号...

And Clojure can call keyword as function, because it implements same interface as function. The same is for symbols...

这篇关于为什么使用关键字或符号作为函数从地图中查找值工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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