On Thu, 04 Dec 2008 23:08:51 +0300, Justin <[EMAIL PROTECTED]> wrote:

Ahh, I thought it would some stupid oversight on my part. This works:

module functionliteral;

import std.stdio;

static void main() {

        int[] values = [1,2,4,8];
        writefln(Reduce(values, function int(int x, int y) { return x + y; }));
        writefln(Reduce(values, function int(int x, int y) { return x * y; }));
}

static int Reduce(int[] values, int function(int x, int y) operation) {
        int total = values[0];
        foreach (int v; values[1..$])
                total = operation(total,v);
        return total;
}


Shorter way:

import std.stdio;
import std.algorithm;

void main()
{
    auto values = [1,2,4,8];

    writefln(reduce!("a + b")(0, values));
    writefln(reduce!("a * b")(1, values));
}

or

import std.stdio;
import std.algorithm;

int add(int a, int b)
{
    return a + b;
}

int mul(int a, int b)
{
    return a * b;
}

void main()
{
    auto values = [1, 2, 4, 8];
    writefln(reduce!(add)(0, values));
    writefln(reduce!(mul)(1, values));
}

but the following doesn't work:

import std.stdio;
import std.algorithm;

void main()
{
    auto values = [1, 2, 4, 8];
    writefln(reduce!((int a, int b) { return a * b; })(1, values));
}

It used to work, IIRC, but now it prints '0'. Does anybody know if it is supposed to work?

Reply via email to