[BEGINNER] reccurence! and sequence!
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 5 17:21:44 PDT 2017
On 07/05/2017 04:38 PM, helxi wrote:
>> ----
>> sequence!((a, n) => a[0] + 1)(1).take(10).writeln;
>> // [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
>> // because a[0] is always 1
>>
>> recurrence!((a, n) => a[0] + 1)(1).take(10).writeln;
>> // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> // because a[0] refers to the previous value
>> ----
>
> Oh thank you. Just 2 follow-up questions:
>> recurrence!((a, n) => a[0] + 1)(1).take(10).writeln;
> 1. In the last example of reccurence, what does n in (a,n) refer to?
n is "the index of the current value". Each time the lambda is called,
a[n] is what is being generated
a[n-1] is the previous value
a[0] is the same as a[n-1]? (I find this confusing)
> 2. How would you chain until! with reccurence? For example I want to
> compute 1, 10, 100, ..., (until the value remains smaller than 1000_000)?
import std.stdio;
import std.algorithm;
import std.range;
void main() {
auto r = recurrence!((a, n) => a[n-1] * 10)(1);
auto u = r.until!(a => a >= 1_000_000);
writeln(u);
}
[1, 10, 100, 1000, 10000, 100000]
Ali
More information about the Digitalmars-d-learn
mailing list