A little challenge...
Igor Lesik
curoles at yahoo.com
Fri Feb 26 01:52:26 PST 2010
"Jason House" <jason.james.house at gmail.com> wrote in message
news:hm75nn$1a2q$1 at digitalmars.com...
> Norbert Nemec Wrote:
>
>> Hi everybody,
>>
>> thinking about array expressions, I have stumbled over an interesting
>> challenge for which I still have no idea:
>>
>> Consider the mathematical sum notation:
>>
>> \sum_i a_i*b_i
>>
>> here, the variable i is defined only at the scope inside the expression.
>>
>> A analogous D syntax could be something like
>>
>> sum!(i)(a[i]*b[i])
>
> Would sum!( "i", "a[i]*b[i]" ) be acceptable? That should be achievable
> with a template mixin that does string mixins under the hood.
I think "i" could be implicit. Here is how I was able to implement it:
void main() {
int[] a = [1,2,3];
int[] b = [4,5,6];
int[] c = [5,4,3];
int IamLazy(){ writeln("am I?"); return 1; }
writeln( sum!("a[i]*b[i]")(a,b) ); // 4 + 10 + 18 = 32
writeln( sum!("b[i]/a[i]")(a,b) ); // 4 + 2 + 2 = 8
writeln( sum!("(a[i]+b[i])%2 + c[i]")(a,b,c) ); // 6 5 4 = 15
writeln( sum!("a[i]*b[i]")(a,b,IamLazy()) );
// fun
writeln( mixin( Msum!("a[i]*b[i]") ) );
writeln( mixin( Msum!("(a[i]+b[i])%2 + c[i]") ) );
}
R _sum(string OP, R : R[], T...)(lazy T op) {
mixin Rename!(T.length);
R ret = 0;
foreach (i; 0 .. op[0].length) {
ret += mixin(OP);
}
return ret;
}
auto sum(string OP, T...)(lazy T op) if (T.length > 0)
{
return _sum!(OP, T[0], T)(op);
}
More information about the Digitalmars-d
mailing list