...

/

Blocks

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 x
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess - x) / x < 0.0001
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else 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 ...