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

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

问题描述

引用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) 的意思相同.见获取.

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天全站免登陆