Bug 12170 – sum(double[]) is not pure nothrow

Status
RESOLVED
Resolution
WORKSFORME
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
All
Creation time
2014-02-15T01:48:00Z
Last change time
2014-04-25T15:03:48Z
Keywords
rejects-valid
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2014-02-15T01:48:01Z
import std.algorithm; void main() pure { [1.0].sum; } dmd 2.065beta3 gives: test.d(3,10): Error: pure function 'D main' cannot call impure function 'std.algorithm.sum!(double[]).sum'
Comment #1 by peter.alexander.au — 2014-02-15T06:09:57Z
The problem is this: "Cyclic functions (i.e. functions that wind up directly or indirectly calling themselves) are inferred as being impure, throwing, and @system." http://dlang.org/function.html sum uses a recursive algorithm for summing floating point ranges for extra accuracy, so its purity is not inferred. It cannot just be marked as pure because the range operations it uses may not be pure. I'm not sure why that cyclic function restriction exists. I think it should be possible to infer these attributes on recursive functions. I'll have a think.
Comment #2 by bearophile_hugs — 2014-02-15T06:43:26Z
Yes, the same happens with nothrow: void main() nothrow { import std.algorithm: sum; [1.0].sum; }
Comment #3 by bearophile_hugs — 2014-02-15T06:49:39Z
(In reply to comment #1) > The problem is this: > > "Cyclic functions (i.e. functions that wind up directly or indirectly calling > themselves) are inferred as being impure, throwing, and @system." Until that compiler limitation is lifted, a solution is to convert the recursive algorithm of sum() in an iterative one. Because sum() is something you often want to use in pure nothrow functions.
Comment #4 by monarchdodra — 2014-02-27T04:05:25Z
(In reply to comment #3) > Until that compiler limitation is lifted, a solution is to convert the > recursive algorithm of sum() in an iterative one. Because sum() is something > you often want to use in pure nothrow functions. Well, "sum" is specifically implemented to do pair-wise sumation of floats, to reduce computational error, as opposed to the "dumber" "member by member" sum. The idea would be to transform the recursive algorithm into an iterative one, but (AFAIK), this usually requires a stack-type structure. Either that, or request better inference for cyclic functions.
Comment #5 by andrej.mitrovich — 2014-04-25T09:29:12Z
It seems to work in git-head now.
Comment #6 by monarchdodra — 2014-04-25T15:03:48Z
Yeah, Kenji recently implemented inference for recursive functions. See also: https://github.com/D-Programming-Language/phobos/pull/2075