Pure higher order functions
KennyTM~
kennytm at gmail.com
Thu Jul 7 09:43:04 PDT 2011
On Jul 7, 11 19:34, bearophile wrote:
> 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
No, I think it's a bug in pure-inference.
pure int h() {
return 1;
}
int f(alias g)() {
return g();
}
pure int i() {
return f!h(); // pure function 'i' cannot call impure function 'f'
}
More information about the Digitalmars-d
mailing list