DEV Community

Discussion on: Challenge: Write the recursive Fibonacci algorithm in a different language.

Collapse
 
slavius profile image
Slavius

I lied a bit. The recursion is there, hidden in the Aggregate function. It's the framework abstraction that masks it.

Otherwise it wouldn't qualify as an answer to OP challenge, or would it? ;)

Thread Thread
 
avalander profile image
Avalander

I know nothing about C#, but I thought that the Aggregate function was somehow invoking an anonymous function here that given current and previous values returns the next element. If that's the case, and it's a function calling another function multiple times instead of the function invoking itself, can we still call it recursion?

Thread Thread
 
slavius profile image
Slavius • Edited

The Aggregate function is member of the Enumerable type and applies an anonymous accumulator function looping all elements in that "array/set". Hard to tell if we can treat it as a recursion. I would have to look at the stack if there are pointers left to the originating caller.

Fibonacci's sequence is strictly sequential so it works well but for more parallel calculations, like SUM, AVG, MAX, MIN accumulator functions you can do:

var result = Enumerable.Range(1,100000)
  .AsParallel()
  .Aggregate(0, (sum, i) => { sum += i } );

And it will multithread across many OS threads to achieve the best efficiency.

Edit: This is however not plain C# .Net anymore but LINQ ;)