Linq语句,用于连续的两半的无限序列 [英] Linq statement for an infinite sequence of successive halves

查看:109
本文介绍了Linq语句,用于连续的两半的无限序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个起始数字,想象一个连续的两半的无限序列.

Given a starting number, imagine an infinite sequence of its successive halves.

1, 0.5, 0.25, 0.125, ...

(忽略double固有的任何数值不稳定性.)

(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 a single-expression way but I found this clever generator code here: http://csharpindepth.com/articles/Chapter11/StreamingAndIterators.aspx

public static IEnumerable<TSource> Generate<TSource>(TSource start,
                                                  Func<TSource,TSource> step)
{
   TSource current = start;
   while (true)
   {
       yield return current;
       current = step(current);
   }
}

您可以使用它:

foreach (double d in Generate<double>(1, c => c / 2))
{
    ...
}

这篇关于Linq语句,用于连续的两半的无限序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆