On Mon, Aug 6, 2012 at 5:32 PM, Philippe Sigaud
<[email protected]> wrote:
> What I'd like to know and may test myself is: is there any speed
> difference in this functional-oriented D code and a more standard
> (C-ish) way to obtain the same result?
Here it is. Answer: no noticeable difference. The functional way also
works at CT, that's great.
Of course, the functional code is (to my eyes) easier to read, easier
to debug and easier to modify.
import std.stdio;
import std.algorithm;
import std.range;
void main()
{
enum max = int.max;
// C-ish
long a,b, temp, sum;
a = 1;
b = 1;
while ( b < max)
{
if (b % 2 == 0) sum += b; // filter and sum
temp = b;
b = a + b;
a = temp;
}
writeln(sum);
// Haskell-ish
writeln(recurrence!((a,n) => a[n-1]+a[n-2])(1L,1L)
.until!(a => a >= max)()
.filter!(a => a%2 == 0)()
.reduce!((a,b) => a+b)());
// Works at CT too!
pragma(msg, recurrence!((a,n) => a[n-1]+a[n-2])(1L,1L)
.until!(a => a >= max)()
.filter!(a => a%2 == 0)()
.reduce!((a,b) => a+b)());
}