Clojure序列理解中是否存在变量?(Are there variables in Clojure sequence comprehensions?)

编程入门 行业动态 更新时间:2024-10-28 06:32:22
Clojure序列理解中是否存在变量?(Are there variables in Clojure sequence comprehensions?)

我正在阅读Programming Clojure第2版,第49页它涵盖了Clojure的for循环结构,它说它实际上是一个序列理解。

作者建议使用以下代码:

(defn indexed [coll] (map-indexed vector coll)) (defn index-filter [pred col] (when pred (for [[idx elt] (indexed col) :when (pred elt)] idx))) (index-filter #{\a} "aba") (0 2)

...优于基于Java的命令式示例,并且给出的证据是“通过使用高阶函数......任何函数索引都避免了对变量的所有需求”。

什么是“idx”,“elt”,如果它们不是变量? 它们是指除累加器之外的变量吗?

另外,为什么#{\ a}而不是“a”?

I'm reading Programming Clojure 2nd edition, and on page 49 it covers Clojure's for loop construct, which it says is actually a sequence comprehension.

The authors suggest the following code:

(defn indexed [coll] (map-indexed vector coll)) (defn index-filter [pred col] (when pred (for [[idx elt] (indexed col) :when (pred elt)] idx))) (index-filter #{\a} "aba") (0 2)

...is preferable to a Java-based imperative example, and the evidence given is that it "by using higher-order functions...the functional index-of-any avoids all need for variables."

What are "idx", "elt" if they are not variables? Do they mean variables besides the accumulators?

Also, why #{\a} instead of "a"?

最满意答案

函数式语言中没有变量。 实际上,您需要区分变量 。 idx它只是一个绑定到具体值的名称,你不能重新分配它( 但你可以将它反弹到另一个值 )。

函数index-filter第一个参数是谓词,表示返回true或false函数。 #{\a}它是一个数据结构set ,但它也可以被视为一个函数。 如果将元素作为参数传递给set函数,则返回此参数(如true ),如果element存在则返回nil(如false )。 因此,您可以将此set谓词视为以更易理解的方式编写的匿名函数#(contains? #{\a} %)

There are no variables in functional languages. Actually, you need distinguish variable and value. idx it's just a name bound to concrete value, and you can not reassign it (but you can rebound it to another value).

First parameter of function index-filter is predicate, that means function that return true or false. #{\a} it's a data structure set, but it also can be treated like a function. If you pass element as argument to set function it returns this argument (like true) if element exists and nil (like false) otherwise. So you can think about this set predicate as anonymous function written in more understandable way #(contains? #{\a} %)

更多推荐

本文发布于:2023-07-19 02:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1171493.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   变量   是否存在   Clojure   sequence

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!