1

I want to create a generator to do, 1 2 3 4.

(defn getNums []
  (loop [i  4
         r []]
    (when (<= i 0)
      r                ;<--- point A
      (recur (dec i) 
             (conj r i)))))

(getNums)  ;Eval to nil. 

Nothing get return, why ?

Would the code in point A return result vector r ?

CodeFarmer
  • 2,644
  • 1
  • 23
  • 32

2 Answers2

2

when, is a clojure macro defined as:

(when test & body)

So, in your first example, the body of when would be:

  (do
  r                
  (recur (dec i) 
         (conj r i)))

The when test itself is evaluated to false so the body of the when macro is not executed. The return value of the function it therefore the return value of when itself is return, which is nil. Ex:

  (when (< 2 1)) ; nil

By the way, there is a build in function range that does the same as your method:

(range 1 10)

And, in a more generic way, you could use the lazy function iterate:

(take 10 (iterate inc 1))
Nicolas Modrzyk
  • 13,961
  • 2
  • 36
  • 40
1
(defn getNums []
  (loop [i  4
         r []]
    (if (<= i 0)
      r
      (recur (dec i) 
             (cons i r)))))

(getNums)
CodeFarmer
  • 2,644
  • 1
  • 23
  • 32