Are there variables in Clojure expressions?

I read Clojure's 2nd Programming Programming, and on page 49 he describes the construction of the Clojure loop, which she says is actually the concept of a sequence.

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) 

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

What are "idx", "elt" if they are not variables? Do they mean variables other than batteries?

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

+4
source share
2 answers
  • Functional languages ​​have no variables. In fact, you need to distinguish between a variable and a value . idx This is just a name bound to a specific value, and you cannot reassign it (but you can bounce it to another value).

  • The first parameter of the index-filter function is a predicate, that is, a function that returns true or false . #{\a} is a set data structure, but it can also be considered as a function. If you pass an element as an argument to the set function, it returns that argument (e.g. true) if the element exists and nil (e.g. false) otherwise. So you can think of this predicate as an anonymous function written in a more understandable way #(contains? #{\a} %)

+4
source

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

As another answer suggests, "no state was created in the creation of this example." idx and elt function as variables, but are local only for understanding the for sequence, so the code is more compact, incompatible and, possibly, clearer (as soon as you get used to sequential understanding, at least :)) - the text may not be optimally intelligible about this question.

+5
source

Source: https://habr.com/ru/post/1436403/


All Articles