Pure higher order functions
bearophile
bearophileHUGS at lycos.com
Thu Jul 7 04:34:37 PDT 2011
With the latest beta update this compiles:
@property bool empty(T)(in T[] a) pure nothrow {
return !a.length;
}
@property ref T front(T)(T[] a) pure nothrow {
assert(a.length);
return a[0];
}
void popFront(A)(ref A a) pure nothrow {
assert(a.length);
a = a[1 .. $];
}
struct Map(alias fun, R) {
R _input;
this(R input) nothrow pure {
_input = input;
}
@property bool empty() nothrow const pure {
return _input.empty;
}
@property auto ref front() nothrow const pure {
return fun(_input.front);
}
void popFront() nothrow pure {
_input.popFront();
}
}
template map(alias fun) {
auto pure map(R)(R range) {
return Map!(fun, R)(range);
}
}
int sqr(int x) pure nothrow { return x * x; }
pure nothrow int foo(int n) {
int total;
foreach (x; map!(sqr)([1, 2, 3, 4]))
total += x;
return total;
}
void main() {
assert(foo(10) == 30);
}
But I have had to write, this I don't know why:
auto pure map(R)(R range) {
And despite Map is a template, its methods aren't pure, so I have had to write them with pure:
@property bool empty() nothrow const pure {
So I think currently map() can't be pure.
I think we need the notion of pure structs/classes (instances).
Bye,
bearophile
More information about the Digitalmars-d
mailing list