Understand Clojure Binding Syntax

I study Clojure and read about doseq when I noticed the example below in the official Clojure doc for doseq

 (doseq [x [-1 0 1] y [1 2 3]] (prn (* xy))) 

My confusion is with the expression [x [-1 0 1] y [1 2 3]] .

Does this expression bind ? I tried some Google search, but could not find the documentation describing such a form.

Can someone help me understand the various syntax representations for form binding in Clojure?

+5
source share
2 answers

This is the required form , in which it "binds" the values ​​from the expression with the name x in turn. Thus, this phrase means the expression that binds the names with the values. It is part of the "destructive binding forms" that bind the names to the parts of the composite value, such as a list or map.

The term "binding" instead of "installation" helps convey the difference between what it does and setting variables in some other programming languages. The name is attached to the time value that is required for the form inside doseq start, then this name is freed to bind to another value.

Clojure offers an arbitrary structural reference for specifying the names of any part of the value in most places in the language that assigns names (anchor characters)

 (doseq [[x1 x2] [[-1 -1] [0 0] [1 1]] y [1 2 3]] (prn (* x1 x2 y))) 

It is also a binding expression, although it looks a little deeper in the data and assigns names to two values ​​for each element in the first vector (and assumes that there are two numbers in each of them). I really love this destruction / binding tutorial

+8
source

It is like a nested for loop in Java. You can also do the manual attachment:

 (dotest (newline) (println "version 1") (doseq [x [1 2] y [:a :b :c]] (println xy)) (newline) (println "version 2") (doseq [x [1 2]] (doseq [y [:a :b :c]] (println xy)))) with results: version 1 1 :a 1 :b 1 :c 2 :a 2 :b 2 :c version 2 1 :a 1 :b 1 :c 2 :a 2 :b 2 :c 

Note that doseq always returns nil and is only suitable for creating side effects (for example, for printing on the screen).

A for expression behaves similarly, but returns a (lazy) sequence of values ​​(note that we generate the vector [xy] for each loop):

 (newline) (println "For generates a (lazy) sequence:" (for [x [1 2] y [:a :b :c]] [xy])) 

with the result:

 For generates a (lazy) sequence: ([1 :a] [1 :b] [1 :c] [2 :a] [2 :b] [2 :c]) 
+2
source

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


All Articles