Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there variables in Clojure sequence comprehensions?

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"?

like image 349
Allyl Isocyanate Avatar asked Jan 16 '23 11:01

Allyl Isocyanate


1 Answers

pred is a function - #{\a} is a set containing the character a. In Clojure, a set is a function which returns true if its argument \a is contained by it. You could also use #(= % \a) or (fn [x] (= \a x)).

As the other answer implies, "no state was created in the making of this example." idx and elt function like variables, but are local only to the for sequence comprehension, so the code is more compact, not stateful, and arguably clearer (once you're used to sequence comprehensions, at least :-) ) -- perhaps the text is not optimally clear on this point.

like image 192
JohnJ Avatar answered Jan 22 '23 02:01

JohnJ