Grabbing a subset of a range if a particular value is found?

Gary Willoughby dev at nomad.so
Tue Sep 24 14:10:49 PDT 2013


On Tuesday, 24 September 2013 at 20:54:30 UTC, Ali Çehreli wrote:
> On 09/24/2013 01:48 PM, Gary Willoughby wrote:> I'm using 
> std.range.recurrence to generate a range but i want to stop it
> > generating and grab the range when a particular value is
> added. e.g.:
> >
> >      recurrence!("a[n-1] + a[n-2]")(1, 2)
> >      .take(10)
> >      .writeln;
> >
> > This writes ten numbers to the command line which is fair
> enough but
> > what would be the preferred method to keep building the range
> until
>
> You said it: until. ;)
>
>   http://dlang.org/phobos/std_algorithm.html#until
>
> > an
> > element calculated is above a particular value.
>
> Ali

Ha! Awesome, thanks!

I'm going to sit down a read the Phobos documentation in its 
entirety one day so i can get a handle on what is available.

I've just started the project euler problems and i'm loving 
exploring the range and algorithm libraries. This is a solution 
to one of the problems.

import std.algorithm;
import std.range;
import std.stdio;

/**
  * Each new term in the Fibonacci sequence is generated by adding 
the previous
  * two terms. By starting with 1 and 2, the first 10 terms will 
be: 1, 2, 3, 5,
  * 8, 13, 21, 34, 55, 89, ... By considering the terms in the 
Fibonacci
  * sequence whose values do not exceed four million, find the sum 
of the
  * even-valued terms.
  */
void main()
{
	recurrence!("a[n-1] + a[n-2]")(1, 2)
		.until!("a > 4_000_000")
		.filter!(a => a % 2 == 0)
		.reduce!("a + b")
		.writeln;
}

I love chaining stuff up like this, it makes the solution easy to 
understand and read. As Walter said in one of his talks, the code 
looks like the problem being solved. I'm loving it! :)


More information about the Digitalmars-d-learn mailing list