gpt4 book ai didi

Scala for 循环 - 在下一个循环中使用 2*i

转载 作者:行者123 更新时间:2023-12-02 01:15:01 25 4
gpt4 key购买 nike

这可能是一个基本的 scala 问题,但无法弄清楚如何:

如何使用 Scala 表达这个 java 循环:

for (int i=1;i<100000;i=2*i)

我知道这是一种可能的方式:

  def loopByTwiceBefore(from:Int, to:Int)(f:Int=>Unit):Unit = {
if (from<to){
f(from)
loopByTwiceBefore(from*2, to)(f);
}
}

但是在 Scala 中是否有更规范的方法来做到这一点。

最佳答案

您可以使用 Iterator 中的 iterate 函数(或来自其他类,如 StreamList 等。 ):

Iterator.iterate(1)(_*2).takeWhile(_ < 100000) foreach {...}

关于Scala for 循环 - 在下一个循环中使用 2*i,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12646721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com