Improvement in pure functions specification

Observer via Digitalmars-d digitalmars-d at puremagic.com
Thu Dec 22 22:53:25 PST 2016


On Thursday, 22 December 2016 at 18:49:02 UTC, Stefan Koch wrote:
> On Thursday, 22 December 2016 at 18:04:51 UTC, Observer wrote:
>
>> (1) Serve as a convenient breakpoint handle in the debugger, 
>> perhaps
>>     as a kind of centralized this_cannot_ever_happen() 
>> function.
>> (2) conditionally_die(conditions);
>> (3) Sleep for some run-time-computable length of time.
>> (4) Yield the thread so other threads can take execution 
>> priority.
>> (5) Yield the entire process so other processes can take 
>> execution
>>     priority.
>> (6) Wait for an external trigger (perhaps a hardware 
>> interrupt, for
>>     instance).
>> (7) Invoke a pass of garbage collection.
>
>
> A function that does any of that cannot be pure.

You judge too quickly.  (1) is certainly possible:

% cat pure.d
pure void cannot_happen_breakpoint () {
     return;
}

int main () {
     cannot_happen_breakpoint();
     return 0;
}
% dmd --version
DMD64 D Compiler v2.071.0
Copyright (c) 1999-2015 by Digital Mars written by Walter Bright
% dmd pure.d
% nm -pr pure | fgrep cannot
0000000000422a60 T _D4pure24cannot_happen_breakpointFNaZv
% gdb pure
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
...
Reading symbols from pure...(no debugging symbols found)...done.
(gdb) break _D4pure24cannot_happen_breakpointFNaZv
Breakpoint 1 at 0x422a64
(gdb) run
Starting program: /home/anon/dlang/pure
warning: the debug information found in "/lib64/ld-2.19.so" does 
not match "/lib64/ld-linux-x86-64.so.2" (CRC mismatch).

[Thread debugging using libthread_db enabled]
Using host libthread_db library 
"/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, 0x0000000000422a64 in 
pure.cannot_happen_breakpoint() ()

With respect to the others, I see in testing that the compiler
objects to a pure function calling an impure function such as
sched_yield().  I was misled in my thinking by the 
nearly-exclusive
focus on memory mutation in the TDPL discussion of pure functions.

Note to Andrei:  in a revised TDPL, this aspect should be 
broadened,
to include explicit mention of other sorts of things that a pure
function is not allowed to do.  Yes, I know the text says "a 
function
is considered pure if returning a result is its only effect", but
from a teaching point of view, that's not enough emphasis to catch
the reader's attention when the entire rest of the discussion is
about mutation.

(Though frankly, I don't know why sched_yield() shouldn't be 
marked
as pure in core.sys.posix.sched.  It's not like a pure function
cannot be interrupted by a timeslice expiration at the OS level,
so calling sched_yield() ought to open no new doors.)


More information about the Digitalmars-d mailing list