def THRESHOLD: Double = 0.0001 def sqr(x: Double): Double = x * x def sqrt_stream(value: Double): LazyList[Double] = { def helper(target: Double, approx: Double): LazyList[Double] = { approx #:: helper(target, approx - (sqr(approx) - target) / (2 * approx)) } helper(value, value) } sqrt_stream(2).take(10).toList def threshold(list: LazyList[Double], thresh: Double) = { list.zip(list.drop(1)).filter(p => math.abs(p._2 - p._1) < thresh).head._2 } threshold(sqrt_stream(2), 1e-15)