pure functions cannot be removed, actually: pure vs. total

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jun 7 21:04:57 UTC 2018


On Thursday, June 07, 2018 20:14:19 Johan Engelen via Digitalmars-d wrote:
> On Tuesday, 5 June 2018 at 14:48:23 UTC, FeepingCreature wrote:
> > I'm just posting to clear up the misunderstanding that a call
> > to a pure function can be removed. Actually, even calls to
> > strongly pure functions cannot always be removed. This is
> > because there is one thing that a pure function can do that
> > will change program behavior if it is removed, even if it does
> > not change any global state whatsoever: it can simply never
> > return.
> >
> > void foo() pure { while (true) { } }
>
> This is not a valid program, in my opinion. (Still only my
> opinion, because I have not found it in the D spec, so needs
> adding.)
> A valid C++ program must make progress in each thread. C++ spec
> states:
> "The implementation may assume that any thread will eventually do
> one of the following:
> - terminate,
> - make a call to a library I/O function,
> - access or modify a volatile object, or
> - perform a synchronization operation or an atomic operation."

I would be _very_ surprised if the D spec said anything like this simply
because it doesn't do a lot of talking about conceptual stuff like this and
talks a lot more about what the compiler actually does (or is supposed to
do) - though that certainly doesn't mean that the spec shouldn't say
something like that, and Walter has previously stated that anything that
needs to be in the spec but isn't should be reported in bugzilla. So, if you
have anything like this that you really think should be in the spec, please
report it in bugzilla.

Regardless, I see zero value in supporting something like

void foo() pure { while(true) {} }

The compiler doesn't actually give an error when using a function like this
(though it does give an error when calling a strongly pure function which
returns a value, and the return value isn't used), but I could easily see it
doing so on the grounds that the function cannot possible be doing any
actual work. And I see _zero_ reason to support something like this just so
that you can run a loop or do other work that gets thrown away. I suppose
that it could be argued that it would be useful for benchmarks, but there
are better ways to handle that that don't require allowing functions that
clearly do no real work.

- Jonathan M Davis



More information about the Digitalmars-d mailing list