I want to create several items for each call to a recursive function, and collect everything in a list. That is, I want to do something like this:
(defn myfunc [x]
(loop [x x retur '()]
(when condition1
(let [templist '()]
(if condition2 (def templist (conj templist {:somekey someval})))
(if condition3 (def templist (conj templist {:somekey someval})))
(recur (+ x 1) (concat retur templist))))))
The problem is that in Clojure I can’t rebind a let. I would like to avoid using global variables.
Some of the functions in core use this pattern of chaining the same symbol through a
letto conditionally build up a value. I had to change contition1 to an example that would not loop forever, and change the when to an if so it could return a value at the end of the loop.which can then be tested:
The idea in the let is to have each stage change the value if the condition is true, or return it unchanged if the condition is false. This pattern gives functional code an imperative look and can help to make it clear how a value is constructed, though it can also be taken too far in using it to “convert” imperative logic into a functional program.