首页 > 解决方案 > 如何实现生成自然数 1、3、5、7...的函数?

问题描述

如何实现生成无限奇数自然数 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)
}

它必须是def oddNats: Stream[Int] = ???

标签: scalastream

解决方案


你可以使用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)


推荐阅读