scala - 如何实现生成自然数 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] = ???
。
解决方案
你可以使用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)
推荐阅读
- flutter - 如何在颤动中使用本地的.svg图标?
- flutter - 如何仅操作 ListView.builder 的一个元素
- socket.io - 如何让 socket.io 与 deno 一起工作?
- python - Python线程锁共享对象无法正常工作
- javascript - 不显示动态 div 中的图像
- python - python游标只返回第一列不为空的那些行
- linux - 如何更改某些文件的扩展名?
- ios - 使用 Accelerate 框架的对称带矩阵的特征值
- php - 从动态 php 文件生成 PDF
- microsoft-graph-api - 不支持endsWith过滤器?