I have started studying Scala on Coursera and have some question on squareRootGuess
implementation as follow
I am trying to implement criteria to filter the accurate guess inside the sqrtGuess
definition as shown below, but it gives me stack overflow error.
def sqrtGuess(x: Double): Stream[Double] = {
def nextGuess(guess: Double): Double = (guess + x / guess)/2
def isSufficient(guess: Double): Boolean = math.abs(x - guess*guess)/x < 0.001
def guesses: Stream[Double] =
1 #:: guesses.map(nextGuess).filter(isSufficient)
guesses
}
But if we define isSufficient outside the sqrtGuess
and apply to sqrtGuess
stream it works out well.
def sqrtGuess(x: Double): Stream[Double] = {
def nextGuess(guess: Double): Double = (guess + x / guess)/2
def guesses: Stream[Double] =
1 #:: guesses.map(nextGuess)
guesses
}
def isSufficient(guess: Double, x: Double): Boolean = math.abs(x - guess*guess)/x < 0.001
sqrtGuess(4.2).filter(isSufficient(_, 4.2)).take(10).toList
I wonder what is happen in the first implementation of sqrtGuess
? I am trying to use substitution model to prove it but it doesn't seems to have any problem.