许多数值问题的形式如下:
initialize: x_0 = ...
iterate: x_i+1 = function(x_i) until convergence, e.g.,
|| x_i+1 - x_i || < epsilon
我想知道是否有一种很好的方法可以使用惯用的 Scala 编写这样的算法。问题的性质要求使用Iterator
or Stream
。但是,我目前对此的看法真的很丑:
val xFinal = Iterator.iterate(xInit) { x_i =>
// update x_i+1
}.toList // necessary to pattern match within takeWhile
.sliding(2) // necessary since takeWhile needs pair-wise comparison
.takeWhile{ case x_i :: x_iPlus1 :: Nil => /* convergence condition */ }
.toList // since the outer container is still an Iterator
.last // to get the last element of the iteration
.last // to get x_iPlus1
这不仅丑陋,模式匹配takeWhile
也会引起警告。显然我不必在这里进行模式匹配,但我希望与数学原件保持强烈的相似性。
有什么想法可以让这个看起来更漂亮吗?