I get 10 of the same result each time for:
(repeat 10 (rand 10))
for example:
=> (2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718 2.54681114871718)
I'm assuming it's some kind of memoization, am I right? How do I get a different value each time?
repeat returns a sequence containing the given value, so (rand 10) is evaluated once as an argument. You can use repeatedly which takes a function:
(repeatedly 10 #(rand 10))
I wouldn't say that this is due to memoization. repeat is just a function, so (rand 10) must be evaluated before repeat can run. That means that
(repeat 10 (rand 10))
Needs to evaluate its argument first, and evaluates to (for example):
(repeat 10 2.54681114871718)
From here, it should be clear why it's returning the same thing over and over again.
To do what you're trying to do, you'd have to use a macro:
(defmacro repeatedlyM [n & body]
`(repeatedly ~n (fn [] ~@body)))
(repeatedlyM 10 (rand 10))
(9.132286678823302
9.767508843398039
5.826387907720001
2.2938644928402283
8.673658990046192
8.112592355036686
2.9539038027898314
2.721946311854755
0.53309774963476
7.258845714766884)
This works because the arguments to macros aren't evaluated before the call like they are with plain functions. (rand 10) is taken literally, placed inside a function, and run many times instead of once.
Just wrapping the code in a function and using repeatedly like the other answer shows though is almost definitely the better solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With