Scala 中的无限流 [英] Infinite streams in Scala

查看:76
本文介绍了Scala 中的无限流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个功能,例如老最爱

Say I have a function, for example the old favourite

def factorial(n:Int) = (BigInt(1) /: (1 to n)) (_*_)

现在我想找到 factorial(n) 适合 Long 的 n 的最大值.我可以做

Now I want to find the biggest value of n for which factorial(n) fits in a Long. I could do

(1 to 100) takeWhile (factorial(_) <= Long.MaxValue) last

这是可行的,但 100 是一个任意的大数;在左侧,我真正想要的是一个无限流,它不断生成更高的数字,直到满足 takeWhile 条件.

This works, but the 100 is an arbitrary large number; what I really want on the left hand side is an infinite stream that keeps generating higher numbers until the takeWhile condition is met.

我想出了

val s = Stream.continually(1).zipWithIndex.map(p => p._1 + p._2)

但是有更好的方法吗?

(我也知道我可以递归地得到一个解决方案,但这不是我想要的.)

(I'm also aware I could get a solution recursively but that's not what I'm looking for.)

推荐答案

Stream.from(1)

创建一个从 1 开始递增 1 的流.它都在 API 文档.

creates a stream starting from 1 and incrementing by 1. It's all in the API docs.

这篇关于Scala 中的无限流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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