Unlike Ben Nadel, I don't intend to post my homework from each day of this exploration but I said in a comment on Ben's blog that I'd post some of my solutions. Today, I'm posting part of my Io Day 2 homework.
fibhelper := method( a, b, c,
if( c <= 1,
fibhelper( b, a+b, c-1 )
fib := method( n,
fibhelper( 1, 1, n )
writeln( "fib(", i, ")=", fib( i ) )
It's weird. This was one of the standard examples everyone always wrote in every new language they learned, back in the day. Yet faced with it yesterday, I drew a complete blank. I wanted to create an infinite lazy sequence of fibonacci numbers and then just walk to the Nth number. It actually took me a while to come up with the code above - and that was after several attempts at a straightforward loop. The recursive version is just the natural way I think, I guess!
I'll try to convert the recursive version into a loop and post that.
OK, now I have the recursive version, here's my iterative version:
fibr := method( n,
f1 := 1
f2 := 1
for( i, 1, n-1,
f := f1 + f2; f1 := f2; f2 = f
writeln( "fib(", i, ")=", fibr( i ) )
Meanwhile, here's Ben Nadel's version of the Io Day 2 homework.