Blocks
In this lesson, you will be introduced to blocks and learn how to set the scope of a program.
In our program for computing the square root of a number, we had to define multiple functions. You might have noticed that most of the functions were very specific to our program and might not be that useful anywhere else. We can better organize our program using a block.
Before we get started, let’s take a look at the code we have written so far.
def abs(x: Double) =if (x < 0) -x else xdef isGoodEnough(guess: Double, x: Double) =abs(guess * guess - x) / x < 0.0001def improve(guess: Double, x: Double) =(guess + x / guess) / 2def sqrtIter(guess: Double, x: Double): Double =if (isGoodEnough(guess, x)) guesselse sqrtIter(improve(guess, x), x)def sqrt(x: Double) = sqrtIter(1.0, x)
Nested Functions
Did you know that you’ve been using blocks this whole time? Blocks are a sequence of expressions wrapped in curly brackets {}
which are ...