F# 创建 x 的倍数列表?
我想创建一个数字的倍数列表。例如[2; 4; 6; 8; 10] 将是 0 到 10 之间 2 的倍数。
我如何动态创建这样一个 x 倍数的列表?是否可以在不设置上限的情况下做到这一点?
一种方法是创建一个介于 0 和某个疯狂的大数字之间的列表,然后使用 mod 函数对其进行过滤。尝试测试这一点时,创建一个 0 到某个疯狂大数字的列表会导致内存不足异常(经过 30 秒左右的等待后)。
我觉得 F# 有一些超级简单且很棒的方法来构建这样的列表,但我还是个新手,还不知道它是什么。帮助?
I want to create a list that is the multiples of a number. For example [2; 4; 6; 8; 10] would be the multiples of 2 between 0 and 10.
How would I dynamically create such a list of the multiples of x? Is it possible to do it without setting an upper bound?
One way to do it would be to create a list between 0 and some crazy large number and then filter it using the mod function. Trying to test this, creating a list of 0 to some crazy large number caused an out of memory exception (after a 30 second or so wait).
I feel like F# has some super simple and awesome way to build such a list but I'm too much of a newb to know what it is, yet. Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这会产生一个无限的倍数序列:
代码稍多,但速度更快:
它基本上相当于以下 C#:
This produces an infinite sequence of multiples:
This is a bit more code, but faster:
It's basically equivalent to the following C#:
序列(IEnumerables)在这里给出了你想要的惰性:
或者使用你的过滤器模型策略:
Sequences (IEnumerables) give the laziness you want here:
or with your filter-mod strategy:
[ 2..2..10] => [2; 4; 6; 8; 10]
其他方式
[ 2..2..10] => [2; 4; 6; 8; 10]
other way
您可以使用参数和
Seq.skip
来获得您需要的任何内容。例如,对于
[2; 4; 6; 8; 10]
:或者:
You can play with the arguments and
Seq.skip
to get whatever you need.For example, for
[2; 4; 6; 8; 10]
:Or: