aceminer
aceminer

Reputation: 4295

Returning a value from a loop

Is there anyway i can return a value from a loop since the recursion has to be at the tail

(ns for)

    (defn abc [y]
    (loop [x 10]
      (when (> x 2)
        (if (= 2 3) (do (println "test") (recur (- x 2)))
        (do (let [x (+ 1 x)
                  y 2] (println y) (recur (- x 2))))))))

    (abc 1)

is there anyway i can return a value for the function by taking y as a parameter and updating a new value of y. However, the recur part has to be at the last line of the code hence i am unable to put y as the last line of the code.

Example

(ns for)

    (defn abc [y]
    (loop [x 10]
      (when (> x 2)
        (if (= 2 3) (do (println "test") (recur (- x 2)))
        (do (let [x (+ 1 x)
                  y 2] (println y) (recur (- x 2)))))))
    y)

    (abc 1)

This would give me an error since recur has to be the last line of code. I have looked at similar questions and it says to put the return value at the end of the if loop which i tried but failed which gives me an exception thatthe recursion can only happen at the tail

Upvotes: 2

Views: 352

Answers (1)

mobyte
mobyte

Reputation: 3752

I guess you meant this:

(defn abc [y]
    (loop [x 10
           y nil]
      (if (> x 2)
        (if (= 2 3)
          (do (println "test") 
              (recur (- x 2) nil))
          (do (let [x (+ 1 x)
                    y 2] 
                (println y) 
                (recur (- x 2) y))))
        y)))

Update. Without unnecessary parts it would be

(defn abc [y]
    (loop [x 10]
      (if (> x 2)
        (do (println 2) 
            (recur (- x 1)))
        2)))

which is the same as

(defn abc [_]
  (dotimes [_ 8] (println 2))
  2)

Upvotes: 9

Related Questions