albusshin
albusshin

Reputation: 4010

What does parallel binding mean in Clojure

I see the binding of recur is "parallel", however I don't get what that means.

I've tested the code below:

(defn parallelTest
  "parallel binding test of recur "
  []
  (loop [vectorA [1 2 3 4 5]
         A (first vectorA)]
    (if-not (= A nil)
      (do (println vectorA) (println A)
        (recur (rest vectorA) (first vectorA)))) ;Recur!
    ))
(parallelTest)

the output is

user=> 
[1 2 3 4 5]
1
(2 3 4 5)
1
(3 4 5)
2
(4 5)
3
(5)
4
()
5
nil

so I assume the bindings are happened simultaneously instead of one by one?

Upvotes: 4

Views: 321

Answers (2)

uselpa
uselpa

Reputation: 18917

Sequential binding

a = 1
b = 2

Here

  1. 1 is evaluated
  2. then bound to a
  3. then 2 is evaluated
  4. then bound to b

Parallel binding

a,b = 1,2

Here,

  1. 1 and 2 are evaluated, either in a determined order (such as left to right) or not, depending on the language specifications
  2. the two results are bound to a and b, respectively.

If the expressions (here 1 and 2) are independant and side-effect free, it doesn't matter which binding you use, but in parallel you need to be aware of the exact evaluation order.

Now, in your case,

  1. first (rest vectorA)
  2. then (first vectorA) are evaluated (left to right)
  3. then the results are bound to vectorA and A, respectively.

which is a parallel binding, as opposed to for example a let binding in Clojure which is sequential.

Upvotes: 3

noisesmith
noisesmith

Reputation: 20194

Yes, in computer science, "in parallel" will generally mean simultaneously, as opposed to "sequentially" (in a specified order) or "concurrently" (in an arbitrary indeterminate order, which could be parallel or sequential with arbitrary sequence). Parallel binding is typically understood to mean that a result (left hand side) of one binding is not in the scope of the creation (right hand side) of another (as opposed to sequential binding, as seen in Clojure's let statement).

Upvotes: 4

Related Questions