Map Purity
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 28 09:15:29 PDT 2015
On Sunday, 28 June 2015 at 15:55:51 UTC, jmh530 wrote:
> My understanding of pure is that a function labeled pure can
> only include pure functions. I've been confused by the fact
> that a function calling map (like below) can be labeled pure
> without any problems. The only way I can rationalize it is that
> map really isn't a function, it's (if I'm understanding it
> correctly) a template that creates a template function that
> calls a struct template.
>
> auto test_map(T)(T x) pure
> {
> return x.map!(a => a + a);
> }
>
> This is related to
> http://forum.dlang.org/thread/ppmokalxdgtszzllzorb@forum.dlang.org?page=1
> but maybe my question is more basic.
There are two aspects to that. First, purity in D is less strict
than the concept in functional programming languages. It allows
access (even mutation) to anything that is reachable through the
parameters. David Nadlinger has written a nice article about the
concept and its implications:
http://klickverbot.at/blog/2012/05/purity-in-d/
Secondly, `map` is indeed a template function, as you write. For
templates functions, the compiler infers many properties,
including purity. Neither the `map` function nor the constructor
of the struct it returns do anything impure, therefore they are
treated as pure. And indeed, the return value of `test_map` will
only depend on its arguments, which is the first requirement for
purity, and of course it doesn't change global state either,
which fulfills the second requirement.
More information about the Digitalmars-d-learn
mailing list