From: Hank Gong Date: 2005-12-13T04:25:28+09:00 Subject: Re: A question about recursive programming ------=_Part_2326_11447302.1134415520163 Content-Type: text/plain; charset=ISO-2022-JP Content-Transfer-Encoding: 7bit Content-Disposition: inline You program works. Mine one listed here: def max(arr) case arr.size when 1 then return arr.first #<---Wrong when arr.first>max(arr[1..-1]) then return arr.first else return max(arr[1..-1]) end end c=[1,2,3,5,10,3,5,2] p max(c) Because the line with wrong comments make error when the max function recurse to the deepest level, my function only print the last elements of array. On 12/13/05, 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 > > ------=_Part_2326_11447302.1134415520163--