Clojure: Idiomatic repetition method with conditional expression-based values

Since recur can only be used in the tail position, how do I return with a value that depends on nested conventions? Here is an example:

(loop [a (rand-int) b 0]
    (if (< a 300)
       (recur (rand-int) 1))
    (if (a < 10000)
       (recur (rand-int) 5))
    b)

The problem is that recurs do not occur in the tail position. So, how do I loop a new value, depending on the internal conditional. I could make a link and change it in conditional expressions, and then return to the tail position, but is there a way to do this without the meaning of a mutation?

+4
source share
1 answer

Duplicate all can be in the tail position:

(loop [a (rand-int 20000) b 0]
    (if (< a 300)
       (recur (rand-int 20000) 1)
       (if (< a 10000)
         (recur (rand-int 20000) 5)
         b)))

Or maybe read a little:

(loop [a (rand-int 20000) b 0]
  (cond 
    (< a 300)   (recur (rand-int 20000) 1)
    (< a 10000) (recur (rand-int 20000) 5)
    :default    b))
+10
source

All Articles