如何实现生成自然数1,3,5,7 ...的函数?

0 scala stream

如何实现生成无限奇数自然数1,3,5,7 ...的函数?

我的尝试是:

def oddNats: Stream[Int] = {
  def loop(a: Int, b: Int): Stream[Int] =
  cons(a, loop(b, a + 2))
  loop(0, 1)
}
Run Code Online (Sandbox Code Playgroud)

它一定是def oddNats: Stream[Int] = ???

nad*_*r.h 6

您可以使用Stream.from(from: Int, step: Int)

def generate(): Stream[Int] = {
    Stream.from(1, 2)
  }

println(generate().take(10).toList) // this will print List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)

Run Code Online (Sandbox Code Playgroud)