Functional purity

The concept of functional purity was discussed briefly back in Chapter 7, Composing Functional Pipelines with Algorithms and Ranges. Now it's time for a quick introduction to functional purity as it is implemented in D. Consider the following function:

Vec2 add(Vec2 a, Vec2 b) pure {
  return Vec2(a.x + b.x, a.y + b.y);
}

Assuming that Vec2 is a struct and not a class, then this function is as pure as a function can be. No global state is mutated, no parameters are mutated, and given multiple calls with the same arguments, the result will be the same every time. Note that it has been marked with the pure attribute. With this, the compiler will produce an error if the function tries to modify any mutable static data (such as a module-scope variable) or if it calls any function not marked pure.

What the compiler does not do is prevent the modification of any reference variables, such as class instances, arrays or ref parameters. This, for example, is legal:

Vec2 add(ref Vec2 a, Vec2 b) pure {
  a.x = 1.0f;
  return Vec2(a.x + b.x, a.y + b.y);
}

In a functional programming language, this sort of thing isn't going to fly. There, only functions like the first version of add are considered pure. In D, such a function is informally referred to as strongly pure, whereas the second version of add would be called weakly pure. The first pass at purity in D did not include the notion of weak purity. The relaxation of the rules came only after experience showed it was necessary. D is not, after all, a functional language, but a language with an imperative core and other paradigms built on top.

For a more in-depth introduction to functional purity in D, and to learn how weak purity actually helps the language better support strong purity, David Nadlinger's blog post Purity in D at http://klickverbot.at/blog/2012/05/purity-in-d/ is a good place to start.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.202.209