0
votes

I need to make loop method, which takes as argument some method name and how many times it will be looped.

Problem is that, i can't use any mutations (def,let and etc) as well as standart clojure functions, except if, inc, dec, println, +, -, = and etc.

Only with SEQ and Recursion !!!

My example:

;; F = some function name, for example, inc, dec, println and etc.

(defn my-loop [f n]
(if (= n 0)
  f
(my-loop f (dec n))))

;; Returns 2, instead of 3, because on next iteration argument F = nil :(

(my-loop (inc 1) 2)

Obviously, when recursion is called, argument F is NIL, so how i can return same argument when recursion was called (without hardcode).

2
SEQ, i mean: next(), first(), seq().Exorsky
Are you looking for (last (take 5 (iterate inc 13)))?akond
Unfortunately, no, i can't use last, take, iterate and other standart functions. I can use this methods only in case if this standart clojure functions is written by myself (also without standart functions)Exorsky
So i need to write all standart clojure functions alghoritm by myself using only SEQ and Recursion.Exorsky

2 Answers

1
votes
(letfn [(my-loop [f n result]
            (if (< n 1) result
                        (recur f (dec n) (f result))))]
    (my-loop inc 2 1))
0
votes

Thanks for help, my solution is:

(defn my-loop [f n result]
(if (< n 1)
  result
(my-loop f (dec n) (f result))))

(my-loop inc 2 1)