[Issue 5510] New: std.functional.iterate

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Jan 31 03:25:42 PST 2011


http://d.puremagic.com/issues/show_bug.cgi?id=5510

           Summary: std.functional.iterate
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 2011-01-31 03:23:24 PST ---
I suggest to add to the std.functional module a higher order function similar
to this one, that's useful in some situations:


/// iterate(f, x, 3) == f(f(f(x)))
auto iterate(F, T)(F f, T z, int n)
    in {
        assert(n >= 0);
    } body {
        foreach (_; 0 .. n)
            z = f(z);
        return z;
    }

import std.stdio: writeln;
import std.math: sin;
void main() {
    writeln(iterate((double x){return sin(x);}, 0.2, 4));
}


Alternative implementation:


import std.functional;

// iterate(f, x, 3) == f(f(f(x)))
auto iterate(alias F, T)(T z, int n)
    in {
        assert(n >= 0);
    } body {
        alias unaryFun!F fun;
        foreach (_; 0 .. n)
            z = fun(z);
        return z;
    }

import std.stdio: writeln;
import std.math: sin;
void main() {
    writeln(iterate!((double x){return sin(x);})(0.2, 4));
    writeln(iterate!((x){return sin(x);})(0.2, 4));
    writeln(iterate!sin(0.2, 4));
}


See also:
http://reference.wolfram.com/mathematica/ref/Nest.html
http://reference.wolfram.com/mathematica/ref/NestList.html

This also suggests:
- The alternative name "nest()" for this higher order function;
- A second function a nestAll() that returns a lazy iterable of all the
intermediate results.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list