[BEGINNER] reccurence! and sequence!
ag0aep6g via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jun 26 03:34:22 PDT 2017
On 06/26/2017 11:51 AM, helxi wrote:
>> auto tri = sequence!((a,n) => n*(n+1)/2)();
>
> /** okay, it's a triangular number array
> * I understand n is the index number, the nth term
> * However where does this 'a' go?
> */
`a` is a tuple of the run-time arguments you pass to `sequence`. In this
example, no arguments are passed (empty parens at the end of the call),
so `a` is empty.
>> auto odds = sequence!("a[0] + n * a[1]")(1, 2);
>
> /** okay, this is a range of odd numbers
> / where and how do I plug (1, 2) into ""a[0] + n * a[1]"
a[0] = 1
a[1] = 2
>> sequence!("n+2")(1).take(10).writeln;
> //[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
`a` isn't used in the string lambda, and it's not considered an element
of the range. So n starts at 0 and this just prints 0+2, 1+2, 2+2, etc.
>> recurrence!("n+2")(1).take(10).writeln;
> //[1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
`a` is still not used in the string lambda, but `recurrence` uses the
values in `a` as the first elements of the range. `n` is incremented
accordingly (to 1), so this prints:
1 = a[0],
3 = (n = 1) + 2,
4 = (n = 2) + 2,
etc.
Another difference between `sequence` and `recurrence` is that `a`
always refers to the same initial value(s) in `sequence`, while in
`recurrence` it gets updated and refers to the previous element(s) of
the range:
----
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
----
More information about the Digitalmars-d-learn
mailing list