多くの数値問題は次の形式です。
initialize: x_0 = ...
iterate: x_i+1 = function(x_i) until convergence, e.g.,
|| x_i+1 - x_i || < epsilon
慣用的な Scala を使用してこのようなアルゴリズムを作成する良い方法があるかどうか疑問に思っています。問題の性質上、Iterator
またはが必要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
も警告を引き起こします。明らかに、ここでパターン マッチングを行う必要はありませんが、元の数学的パターンとの類似性を維持したいと考えています。
これをより美しく見せるためのアイデアはありますか?