Thursday, December 01, 2011

Fibonacci Numbers the Weird Way

Yanniel recently posted two ways to generate Fibonacci numbers, here are two more.

Generating Fibonacci numbers with an enumerator

for i in Fibonacci(10) do
    Writeln(i);
Of course you need a Fibonacci-implementing enumerator. I wrote one on 2007 and it uses the iterative approach. Read more in my old article Fun with enumerators, part 6 – generators.

Generating Fibonacci numbers with anonymous methods

This one was prepared for ITDevCon 2011 as an example of tricky (but pretty much useless) example of what can be done using anonymous methods.

var
    fib: TFunc<integer>;
begin
    fib := Fibonacci(10);
    Writeln(fib());
end;
In this example, Fibonacci(10) call doesn’t really calculate Fibonacci numbers. It only sets up a recursive anonymous method that calculates one specific Fibonacci number (in case the tenth element) when it is executed by calling fib().
function FibonacciList(elNum: integer): TFunc<integer>;
var
    el1: TFunc<integer>;
    el2: TFunc<integer>;
begin
    if elNum = 1 then
        Result := function: integer
        begin
            Result := 0;
        end
    else if elNum = 2 then
        Result := function: integer
        begin
            Result := 1;
        end
    else begin
        el1 := FibonacciList(elNum-1);
        el2 := FibonacciList(elNum-2);
        Result := function: integer
        begin
            Result := el1() + el2();
        end;
    end;
end;

function Fibonacci(elNum: integer): TFunc<integer>;
begin
    Result := FibonacciList(elNum);
end;
[A note to ITDevCon audience – this is updated version of the code I’ve shown in Verona. A note to Yanniel’s readers – he’s counting numbers from 0, I’m doing it from 1 so his Fibonacci(9) is my Fibonacci(10).]

No comments:

Post a Comment