Pure higher order functions

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 7 10:40:55 PDT 2011


On 2011-07-07 04: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).

And what would that even mean? Purity for types makes no sense. It only makes 
sense for functions. What it sounds like is that the purity inference isn't 
working when it's the type which is templated instead of the function. If 
that's the case, then the purity inference needs to be improved. But it's 
brand new, so it's no surprise if it doesn't work entirely correctly.

- Jonathan M Davis


More information about the Digitalmars-d mailing list