clojure - why this code is wrong ? How does 'recur' work? -
i don't know why code below wrong:
(defn factorial [n] (loop [n n acc 1] (if (zero? n) acc (recur (* acc n)(dec n))))) (= 1 (factorial 1)) how recur work?
the arguments recur wrong way round.
nshould become(dec n)accshould become(* acc n)
so should
(recur (dec n) (* acc n)) we can recast given algorithm see what's going on inside it.
if represent pair of arguments vector, function generates next pair is
(fn [[n acc]] [(* acc n) (dec n)]) we can generate endless sequence of possible pairs given noby applying iterate function above, starting [no 1].
(fn [no] (iterate (fn [[n acc]] [(* acc n) (dec n)]) [no 1])) applying 1 generates
([1 1] [1 0] [0 0] [0 -1] ...) we stop @ element 2, first initial 0, returning other 0.
if put arguments right way round, can proper factorial thus:
(defn factorial [no] ((comp second first) (drop-while (comp not zero? first) (iterate (fn [[n acc]] [(dec n) (* acc n)]) [no 1])))) this returns second element of first pair in sequence 0 first (duh!).
hopelessly overcomplicated normal use, work?
=> (map factorial (range 6)) (1 1 2 6 24 120) yes.
Comments
Post a Comment