Reputation: 109
I wrote this "code" to show the problem since the actual code is quite big
(defn add-list
([number]
(def used [number])
(add-list number used))
([number used]
;Add elements to used
;Process the elements in used
;Find the next number
(add-list number used)
))
I need to have a vector that I can access in the fn that will allow me to process the items inside the vector and then add the output to the vector so that the old items and the new items are in this vector for the next cycle.
I got it working by defining the vector above the add-list function but if I run the program on repl a second time the vector doesn't get cleared. It also says the vector is unbound sometimes.
Upvotes: 0
Views: 64
Reputation: 29958
The reduce
function can be used to accumulate a list of results, not just sum values:
(defn accum-reverse
[cum-state curr-val]
(cons curr-val cum-state))
(println
(reduce accum-reverse
[] ; initial value of cum-state
[1 2 3 4 5] ; fed into curr-val one at a time
))
;=> (5 4 3 2 1)
The function accum-reverse
is called 5 times. The first time cum-state
is the initial value of []
, the empty vector. Each subsequent time cum-state
is set to the previous return value fromaccum-reverse
.
Besides the online docs, you can also get some good information from Clojure for the Brave & True. Most of it is online, but it is also worth a purchase.
Upvotes: 1