pure functions

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 12 23:59:10 PDT 2016


On Tuesday, September 13, 2016 03:33:04 Ivy Encarnacion via Digitalmars-d-
learn wrote:
> Can pure functions throw exceptions on its arguments? Also, how
> can it perform impure operations?

Yes, as long as the exception's constructor is pure, a pure function can
throw an exception. However, whether a pure function can do impure
operations depends on what you mean by that. A pure function cannot call any
function that is not pure (except in debug blocks, which circumvent pure
purely for debug purposes and should not be used in normal code). That's
part of being pure. But "pure" in the D sense really doesn't have anything
to do with functional purity except insofar as it helps enable functional
purity, so if when you're talking about a pure function doing an impure
operation, you mean doing something that isn't functionally pure, then it
can so long as the function's that it's calling are all pure.

_All_ that pure means in D is that the function cannot access any mutable,
global state or call any functions that aren't pure. At this point, it would
be far more accurate for it to be called @noglobal than pure, but it's pure
because when it was introduced, it was much closer to functionally pure (but
far less useful). Originally, pure functions had to have parameters which
were immutable or implicitly convertible to immutable so that the function
could be functionally pure. That requirement no longer exists, but when a
pure function does meet those requirements, there are optimizations that the
compiler can do based on functional purity. For instance, a pure function
which is functionally pure (i.e. if given the same arguments, it will always
result in the same return value) will only be called once with a given set
of arguments within an expression even if it's called multiple times. e.g.

auto result = pureFunc(a) * pureFunc(a);

would result in only one call to pureFunc if pureFunc's parameters are
immutable or implicitly convertible to immutable, and the result will be
reused. But if the paramaters are not immutable or implicitly convertible to
immutable, then it's not functionally pure, and the calls cannot be
optimized. Most pure functions can't be optimized like that. On the whole,
pure is just a way to guarantee that a function is only using what it's
given via its arguments and not doing stuff like saving state in static or
global variables. Being able to optimize based on pure when it's actually
functionally pure is a just a nice bonus that pops up occasionally.

For a more in-depth look at D's purity, you should read

http://klickverbot.at/blog/2012/05/purity-in-d/

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list