Clojure for loop, save values ​​in set or map

This person bothered me for a while. How to save a value in a set or map in a for loop?

(let [s #{}] (for [ i (range 10) j (range 10) ] (into s [ij]))) 

I know that this will not work, but I want functionality similar to it, where in the end the set will contain [0 0] [0 1] ... [0 9] [1 0] ... [9 9]

thanks

+7
source share
5 answers

If I understand your question correctly, you need to invert the expression from the inside:

 (let [s #{}] (into s (for [i (range 10) j (range 10)] [ij]))) 

Here you need to understand that for returns a value (lazy sequence) in contrast to for-loops in more imperative languages ​​such as Java and C.

+13
source

Is this what you want?

 (into #{} (for [i (range 10) j (range 10)] [ij])) ;-> #{[2 1] [3 2] [4 3] [5 4] [6 5] [7 6] [8 7] [9 8] [1 0] ; [2 2] [3 3] [4 4] [5 5] [6 6]... 

And if you just need a list as a set:

 (set (for [i (range 10) j (range 10)] [ij])) 

As a result, you get a set of pairs.

+6
source

Usually, when you want to return a collection or map or another “single value” that is not seq from a “repeated” generalized operation in seq, using reduce more idiomatic / direct than loop/recur , and for always returns seq (not a collection or map).

 (reduce conj #{} (for [i (range 10) j (range 10)] [ij])) 

note that (for ..) is used here only to create a seq containing all the values ​​to compile into a single set result. Or, for example:

 (reduce + 0 (range 100)) => 4950 
+5
source

clojure has some great systems for managing variable state. in this case you may need an atom containing a set

your other options:

  • a ref if you want to make several changes (many threads agreed)
  • a var if it is single-threaded (var may also work here as an atom)
  • a agent , if you want to set s asynchronously

of course for returns a sequence so you can just want

  (into #{} (for [ i (range 10) j (range 10) ] [ij])) 
0
source

I think you can also use some structure of temporary data in this scenario.

 (let [s (transient #{})] (for [ i (range 10) j (range 10) ] (assoc! sij))) (persistent! s) 

Just a sample code, not verified.

0
source

All Articles