From: Matthew Desmarais Date: 2005-12-13T04:14:05+09:00 Subject: Re: A question about recursive programming mental@rydia.net wrote: >Quoting Hank Gong : > > > >>And also I think it's not easy to think every loop as recursive >>way. >> >> > > > >>For example it's very difficult to write max function by >>recursive function. >> >> > >iterative: > > def max( *values ) > case values.size > when 0 > nil > when 1 > values[0] > else > i = 1 > max = values[0] > while i < values.size > max = values[i] if values[i] > max > i = i + 1 > end > max > end > end > >recursive: > > def max( *values ) > case values.size > when 0 > nil > when 1 > values[0] > else > max_helper( values, 1, values[0] ) > end > end > > def max_helper( values, i, max ) > if i < values.size > max = values[i] if values[i] > max > max_helper( values, i + 1, max ) > else > max > end > end > >-mental > > So: An empty list has no max. The max of a list containing one element is that element. The max of a list containing more than one element is the greater of the first element and the max of the rest of the list. def recursive_max(an_array) if (an_array.size < 2) an_array.first else rest_max = recursive_max(an_array[1..-1]) an_array.first > rest_max ? an_array.first : rest_max end end Regards, Matthew