我正在阅读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} %)
更多推荐
发布评论