D puts an emphasis on functional programming and provides first-class support for development in a functional style.
In D a function can be declared as pure
which implies
that given the same input parameters, the same output
is always generated. pure
functions cannot access or change
any mutable global state and are thus just allowed to call other
functions which are pure
themselves.
int add(int lhs, int rhs) pure {
impureFunction(); // ERROR: unable to call impureFunction here
return lhs + rhs;
}
This variant of add
is called a strongly pure function
because it returns a result dependent only on its input
parameters without modifying them. D also allows the
definition of weakly pure functions which might
have mutable parameters:
void add(ref int result, int lhs, int rhs) pure {
result = lhs + rhs;
}
These functions are still considered pure and can't access or change any mutable global state. Just passed-in mutable parameters might be altered.
Due to the constraints imposed by pure
, pure functions
are ideal for multi-threading environments to prevent
data races by design. Additionally pure functions
can be cached easily and allow a range of compiler
optimizations.
The attribute pure
is automatically inferred
by the compiler for templated functions and auto
functions,
where applicable (this is also true for @safe
, nothrow
,
and @nogc
).