Reputation:
How does this recursive function work step by step:
(fn foo [n]
(if (< n 10)
[n]
(conj (foo (quot n 10))
(mod n 10))))
I have problem with understanding: lets say i give it as n
the number 123, and it will return a vector of its digits. At the last step when arrived to 1
and (< 1 10)
it should go to the then-part [n]
, return [1] and come out of the recursion. So this doesn't happen, what am i missing in the play?
Upvotes: 0
Views: 112
Reputation: 13483
At the last step when arrived to 1
and (< 1 10)
it does go to the then-part [n]
, return [1], but it does NOT come out of the recursion, only out of the innermost invocation.
The evaluation goes as follows:
(foo 123)
(conj (foo 12) 3)
(conj (conj (foo 1) 2) 3)
(conj (conj [1] 2) 3)
(conj [1 2] 3)
[1 2 3]
Upvotes: 2