为什么“(def vowel?(set”aeiou“))”工作? [英] why does "(def vowel? (set "aeiou"))" work?

查看:126
本文介绍了为什么“(def vowel?(set”aeiou“))”工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来看一看卓越的Clojure教程这里。在其中一个示例中,它具有沿着以下行的Clojure代码:

I'm taking a look at the excellent Clojure tutorial here. In one of the examples it has Clojure code along the following lines:

(def vowel? (set "aeiou"))

这使元音对元音返回true,辅音返回false:

This makes vowel return true for vowels and false for consonants:

(vowel? (first "abc")) ; => true
(vowel? (first "cba")) ; => false

为什么?我假设它与变量名后面的问号有关。在教程中找不到任何东西...

Why is this? I'm assuming it has something to do with the question mark behind the variable name. Couldn't find anything right away in the tutorial...

编辑 vowel?不返回true或false,而是元素本身或nil。

Edit I just realized vowel? doesn't return true or false but rather the element itself or nil. See my own answer.

推荐答案

这完全类似于地图(Clojure中最自然的对象)是如何工作的。当地图作为一个函数调用时,它作为一个映射:

This is perfectly analogous to how maps (the most natural objects in Clojure) work. When the map is called as a function, it works as a mapping:

user=> (def ob {:foo "bar", :bar :baz, :qwerty 42})
#'user/ob
user=> (ob :foo)
"bar"

被称为一个函数,并将作为一个成员测试。顺便说一句,如果您使用关键字(以冒号开头的那些东西)作为映射的键,它们也可以用作类似的函数,因此您可以执行

So it makes sense that a Clojure set can be called as a function, and will work as a membership test. By the way, if you use keywords (those things that start with a colon) as the keys of a mapping, they also work as similar functions, so you can do

user=> (:bar ob)
:baz

user=> (def vowel-keywords (set [:a :e :i :o :u]))
#'user/vowel-keywords
user=> (:a vowel-keywords)
:a
user=> (:b vowel-keywords)
nil

但是,使用关键字,而不是您可能在映射中用作键或集合中的成员的任何其他内容。

But, again, this latter trick only works with keywords, not anything else that you might use as keys in a mapping or members in a set.

这篇关于为什么“(def vowel?(set”aeiou“))”工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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