Scala for the Impatient Second Edition

My highlights and comments

"To define a function, specify the function’s name, parameters, and body like this:

def abs(x: Double) = if (x >= 0) x else -x" (Chapter 2.7)

I defined and used an almost identical function to get the absolute value, with the following code:

1+3
def abs(x: Double) = if (x < 0) -x else x

def sqrt(x: Double) = {
def isGoodEnough(guess: Double) =
abs(guess * guess - x) / x < 0.001

def improve(guess: Double) =
(guess + x / guess) / 2

def sqrtIter(guess: Double): Double =
if (isGoodEnough(guess)) guess
else sqrtIter(improve(guess))

sqrtIter(1.0)
}

sqrt(2)
sqrt(4)
sqrt(1e-6)
sqrt(1e60)


This was the output:

val res0: Int = 4

def abs(x: Double): Double

def sqrt(x: Double): Double

val res1: Double = 1.4142156862745097
val res2: Double = 2.000609756097561
val res3: Double = 0.0010000001533016628
val res4: Double = 1.0000788456669446E30


Created: 2021-06-06 02:16:07 Last updated: 2021-06-06 02:16:07

Top