From: Robert Klemme Date: 2010-01-04T02:25:08+09:00 Subject: Re: Few clarifications on recursion On 01/03/2010 05:52 PM, Phillip Gawlowski wrote: > On 03.01.2010 17:16, Panagiotis Atmatzidis wrote: > >> Although it introduces many interesting concepts to me (i. e. I did not knew that after the "if" statement a single _1_ with no quotes could be used) I fail to see how the num changes value. The way I read the code here: >> >> num * factorial(num-1) >> >> is 30*29 for "puts factorial(30)" not 30*29*28... which is how it works. I've tested the code works fine. >> >> The book although, in my opinion is excellent (so far) for starters, does not explain - or it does but I did not understand it nevertheless - how this piece of code works. > > In a nutshell, recursion means performing the same action until a > condition is met. Actually that description is true for loops (aka iterations) as well. :-) The important bit of recursion - and the part where recursion and iteration differ - in programming languages is, that it needs a _function (or method)_ which calls _itself_. Most of the time it happens directly (as in this example) but it may as well happen indirectly (f calls g, g calls f) although I cannot think of a reasonable example right now. (Most indirect recursions are probably programming errors which you notice when a SystemStackError pops up. :-)) Certain forms of recursion can actually be transformed into iterations (which some programming languages / runtimes actually do). That way you usually get better performance. See http://en.wikipedia.org/wiki/Tail_recursion Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/