Comment #0 by bearophile_hugs — 2011-01-31T03:23:24Z
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.htmlhttp://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.
Comment #1 by bearophile_hugs — 2011-02-02T02:25:48Z