Can I do nested for statements that refer to earlier bindings?

I’m trying this: however, It explodes on me because apparently it isn’t valid syntax that the more left binding form refers to the right binding form. Now, I can do this by replacing the right-side with a map statement; but is there a syntactic trick for doing this purely in the for statement?

Pseudo-code: Given a collection of collections, for each 1st-level collection, partition it; then for each partition, do a calculation based on the two elements of that partition.

(let [nested-data [[1 "bat" 2 "frog"] [1 "puppy" 2 "kitty"]] ]
				(for [[[size source] [_ target]]
				      (partition 2 1 branch)
				      branch nested-data]
				  (str "The " source " takes " size " steps toward the " target))) 
;; desired output: 
;; ("The bat takes 1 steps toward the frog" "The puppy takes 1 steps toward the kitty")

Here’s a working version with map. I’m just wondering about the let binding sequence and what’s possible there.

(let [nested-data [[[1 "bat"] [2 "frog"] [3 "snake"]]
                   [[1 "puppy"] [2 "kitty"] [3 "parakeet"]]]]
  (for [[[size source] [_ target]] (mapcat #(partition 2 1 %) nested-data)]
    (str source " took " size " steps toward " target)))
;; ("bat took 1 steps toward frog"
;;  "frog took 2 steps toward snake"
;;  "puppy took 1 steps toward kitty"
;;  "kitty took 2 steps toward parakeet")

Talking this through with a colleague we found that you CAN refer to other things in the for binding sequence – unexpected to me was that, although right-more represents the outer loops, references are available in a left-first manner. In other words, for [a acoll b (map first a)] works, because b can refer to the a on its left. But it seems that the “faster” inner cycle (lefter) CANNOT refer to the slower outer-cycle (righter).

Well, sanity-checking with my faith in the clojure devs paid off. RIGHTER is faster, so it DOES make sense that it can refer to lefter definitions. I’m glad the clojure devs are so smart.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.