On Sunday, 28 May 2017 at 23:49:16 UTC, Brad Roberts wrote:
Is there a mechanism for declaring something pure when it's built from parts which individually aren't?

string foo(string s)
{
// do something arbitrarily complex with s that doesn't touch globals or change global state except possibly state of the heap or gc
    return s;
}

Ali has answered this two years ago:

http://www.digitalmars.com/d/archives/digitalmars/D/learn/using_memset_withing_a_pure_function_74629.html#N74631

Copying for convenience:


If you want to live dangerously, you can use assumePure, which is found
in one of the unittest blocks of std.traits:

import std.traits;

auto assumePure(T)(T t)
if (isFunctionPointer!T || isDelegate!T)
{
     enum attrs = functionAttributes!T | FunctionAttribute.pure_;
return cast(SetFunctionAttributes!(T, functionLinkage!T, attrs)) t;
}

int i = 0;

void foo()
{
     ++i;    // foo accesses mutable module-level data
}

void bar() pure
{
     auto pureFoo = assumePure(&foo);
     pureFoo();    // <-- pure function is calling impure function
}

void main()
{
     assert(i == 0);
     bar();
     assert(i == 1);    // mutation through a pure function
}

It also came up in other discussions (the keyword is `assumePure`), e.g.
- http://forum.dlang.org/post/hpxxghbiomtitrmwe...@forum.dlang.org
- http://forum.dlang.org/post/nfhqvffqtkfsxjewg...@forum.dlang.org

Reply via email to