D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4111 - Foreach ranges accept floating-point extrema
Summary: Foreach ranges accept floating-point extrema
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2010-04-21 14:01 UTC by bearophile_hugs
Modified: 2022-03-22 12:50 UTC (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2010-04-21 14:01:40 UTC
This D2 code works with dmd 2.043, it shows that foreach accepts floating point extrema too.

But I think it's safer/tidier to accept only ranges with integral extrema (in Python too the range/xrange expects integers). FP approximations can cause problems here.


import std.stdio;
import std.math: nextUp;
void main() {
    foreach(i; 2.1 .. 4.10001) {
        writeln(typeid(typeof(i))); // Output: double
        break;
    }
    foreach(i; 2.1 .. nextUp(4.1))
        write(i, " "); // Output: 2.1 3.1 4.1
}
Comment 1 bearophile_hugs 2010-04-22 02:09:06 UTC
Aelxx (aelxx at yandex dot ru) suggests:

I'd like MATLAB style more:
foreach (f; linspace (0.0, 1.0, 100))
{...}
here f gets values 0, 0.0101.., 0.0202..., ..., 0.98989..., 1.0

foreach (f; logspace (1.0, 1e6, 7))
{...}
here f gets values 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6.

------------------------

My answer:

Phobos has iota() that's similar to what you ask, a FP version is easy to create. With iota even the current interval syntax becomes less useful.
See also bug 4112.
Comment 2 Johannes Loher 2018-05-05 11:59:34 UTC
This still works as of 2.080.0 and the spec indeed does not state that only integral extrema are allowed. This is legal code at the moment. I'll tag this as enhancement.
Comment 3 RazvanN 2022-03-22 12:50:49 UTC
This issue has been filled a long time ago and there were no other complaints. Since it is possible that code in the wild uses this feature (in spite of FP approximations), I see no point in dissallowing it.