Given a starting number, imagine an infinite sequence of its successive halves.
1, 0.5, 0.25, 0.125, ...
(Ignore any numerical instabilities inherent in double
.)
Can this be done in a single expression without writing any custom extension methods or generator methods?
I don't know of any way to make an infinite sequence with straight LINQ. But you could make a very long sequence.
However, since
double
has finite precision, you'll get nothing but zeroes aftern
gets too high.For fun, here's a trick to create a real infinite sequence in a single expression. The first two definitions are class fields, so that they do not require an expression to be initialised.
It isn't actually infinite, but as both
Repeat
andSelect
use deferred execution, you won't lose any performance.Don't know any native way to create infinite linq expression.
Or you can manually write infinite version of
.Repeat
Here is an answer similar to the one @hvd provided, but using the
Y
operator defined here, this removes the need for the local variables:An example use would be:
Which would output 20, 10, 5, 2.5 etc...
I wouldn't advise using this in production code but it is fun.
The
Y
operator also allows other recursive lambda expressions, e.g:I don't know of a single-expression way but I found this clever generator code here: http://csharpindepth.com/articles/Chapter11/StreamingAndIterators.aspx
In your case you'd use it: