The disadvantage of purity

Paul Backus snarwin at gmail.com
Sun Dec 29 12:30:15 UTC 2019


On Sunday, 29 December 2019 at 10:46:07 UTC, Dominikus Dittes 
Scherkl wrote:
> On Sunday, 29 December 2019 at 10:02:48 UTC, berni44 wrote:
>
>> The problem is, that this function should indeed return 
>> something different, when it calls itself (indirectly) with 
>> identical parameters once more to prevent the original call 
>> from never returning...
>
> This should indeed be NOT the same parameters. There should be 
> a hidden additional parameter (lets name it "called_internal"), 
> that be false in the original call and true in a recursion. 
> With this it's perfectly pure while returning something 
> different if called by itself.

The problem with this approach is that the recursion may not be 
direct. For example:

import std;

struct A
{
     B[] bs;
     void toString(W)(ref W w) { formattedWrite(w, "%s", bs[0]); }
}

struct B
{
     C[] cs;
     void toString(W)(ref W w) { formattedWrite(w, "%s", cs[0]); }
}

struct C
{
     A[] as;
     void toString(W)(ref W w) { formattedWrite(w, "%s", as[0]); }
}

void main()
{
     A[] as = [A()];
     B[] bs = [B()];
     C[] cs = [C(as)];
     as[0].bs = bs;
     bs[0].cs = cs;

     writeln(as[0]); // crashes
}

Solving this is probably halting-equivalent in the general case 
(that is, impossible), so I'm not inclined to worry too much 
about it. If someone writes an infinite loop in their toString 
method, that's their problem.


More information about the Digitalmars-d mailing list