www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Current purity offenders

As Phobos develops more, there are some commonly used Phobos functions that
aren't pure yet:

import std.algorithm, std.typecons, std.conv, std.array, std.range;
pure auto foo(int[] a) {
    auto a2 = array(iota(a.length)); 
    return tuple(text(a), a2);
void main() {}

But a function like text() may call toString(), that's not always pure, so D
needs the conditionally purity to implement a conditionally pure text() (or
text code needs to be duplicated with a pure version, but probably this is not
an option).

Random number generation too is useful in pure functions, see:

// strongly pure
pure double[] foo(const int n, const double firstSeed=42) {
    double seed = firstSeed;
    auto res = new double[n];
    foreach (ref r; res) {
        auto seed_rnd = nextRandom(seed, 1.0);
        r = seed_rnd.rnd;
        seed = seed_rnd.seed;
    return res;

When such parts of Phobos will become (conditionally) pure, it will become much
simpler to write D small programs as a small impure I/O part that calls mostly
pure functions/methods :-) Simon Peyton-Jones says this is one of the most
important qualities of Haskell, and from what I'm seeing, it's not a bad thing.

Mar 24 2011