purity question

Stefan Koch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 28 18:01:46 PDT 2017


On Monday, 29 May 2017 at 00:53:25 UTC, Brad Roberts wrote:
> On 5/28/2017 5:34 PM, Jonathan M Davis via Digitalmars-d-learn 
> wrote:
>> On Sunday, May 28, 2017 16:49:16 Brad Roberts via 
>> Digitalmars-d-learn 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;
>>> }
>> <snip lecture> you can cast </snip lecture>
>>
>
> Ok, so there essentially isn't.  I'm well aware of the risks of 
> lying to the compiler, but it's also not sufficiently smart to 
> unravel complex code.  Combined with there being interesting 
> parts of the standard libraries that themselves aren't marked 
> pure, there's a real need for escape hatches.  A simple 
> example: anything that has a malloc/free pair.

There is

void[] myPureMalloc(uint size) pure @trusted nothrow @nogc
{
    alias pure_malloc_t = pure nothrow void* function(size_t size);
    return (cast(pure_malloc_t)malloc)(size)[0 .. size];
}


More information about the Digitalmars-d-learn mailing list