Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass data to next iteration in (for ...)?

Tags:

clojure

I am in the progress of learning clojure after work and I'm doing this by making a small game (loving the quil library) to make me familiar with the different aspects of clojure in specific and FP in general.

So, my game world exists of 3d grid of map data strucutures (vector of a vector of a vector of a map). I want to itterate over every point in 3d space (map) and change the data when a condition is met. This was my initial solution:

(the game data structure is the game state (a map))

(defn soil-gen [game]
  (let [world-x (game :world-x)
        world-y (game :world-y)
    world-z (game :world-z)]
      (for [x (range world-x) 
          y (range world-y) 
          z (range world-z) 
          :when (> z (* world-z (rand)))]
         (assoc-in game [:world x y z :type] :soil))))

But this returns a list of the results (my game state data structure) of every iteration instead of one game data structure. I should somehow be able to pass the result of each iteration back to for. Something like loop/recur probably but I think you cant combine recur with for.

Somebody a clue?

thanks

like image 385
user1782011 Avatar asked Oct 29 '12 06:10

user1782011


People also ask

How do you continue to next iteration in for loop?

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement.

How do you go to next iteration in Python?

The continue statement instructs a loop to continue to the next iteration. Any code that follows the continue statement is not executed. Unlike a break statement, a continue statement does not completely halt a loop. You can use a continue statement in Python to skip over part of a loop when a condition is met.

What does pass do in a for loop?

pass simply does nothing, while continue goes on with the next loop iteration.


1 Answers

What you can do is use reduce with for as shown below:

(defn soil-gen [game]
  (let [world-x (game :world-x)
        world-y (game :world-y)
    world-z (game :world-z)]

    (reduce (fn [g [x y z]] (assoc-in g [:world x y z :type] :soil)))
            game
            (for [x (range world-x) 
                  y (range world-y) 
                  z (range world-z) 
                 :when (> z (* world-z (rand)))]
                 [x y z]))))
like image 131
Ankur Avatar answered Sep 18 '22 00:09

Ankur