在 Scala 中使用 Streams 进行迭代 [英] Using Streams for iteration in Scala

查看:42
本文介绍了在 Scala 中使用 Streams 进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SICP 说迭代过程(例如平方根计算的牛顿方法、pi"计算等)可以用Streams来表述.

SICP says that iterative processes (e.g. Newton method of square root calculation, "pi" calculation, etc.) can be formulated in terms of Streams.

有人在 Scala 中使用 streams 来模拟迭代吗?

Does anybody use streams in Scala to model iterations?

推荐答案

这是产生 pi 近似值流的一种方法:

Here is one way to produce the stream of approximations of pi:

val naturals = Stream.from(0) // 0, 1, 2, ...
val odds = naturals.map(_ * 2 + 1) // 1, 3, 5, ...
val oddInverses = odds.map(1.0d / _) // 1/1, 1/3, 1/5, ...
val alternations = Stream.iterate(1)(-_) // 1, -1, 1, ...
val products = (oddInverses zip alternations)
      .map(ia => ia._1 * ia._2) // 1/1, -1/3, 1/5, ...

// Computes a stream representing the cumulative sum of another one
def sumUp(s : Stream[Double], acc : Double = 0.0d) : Stream[Double] =
  Stream.cons(s.head + acc, sumUp(s.tail, s.head + acc))

val pi = sumUp(products).map(_ * 4.0) // Approximations of pi.

现在,假设您想要第 200 次迭代:

Now, say you want the 200th iteration:

scala> pi(200)
resN: Double = 3.1465677471829556

...或第 300000 个:

...or the 300000th:

scala> pi(300000)
resN : Double = 3.14159598691202

这篇关于在 Scala 中使用 Streams 进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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