val pi = 3.14
def circumference(r: Double): Double = {
val pi = 3.14159
2.0 * pi * r
}
def area(r: Double): Double =
pi * r * r
pi: Double = 3.14 defined function circumference defined function area
The purpose of this exercise is to warm up on the concepts of binding and scope, by example, in Scala.
For each the following uses of variable names, give the line where that name is bound. Briefly explain your reasoning (in no more than 1–2 sentences).
Consider the following Scala code:
val pi = 3.14
def circumference(r: Double): Double = {
val pi = 3.14159
2.0 * pi * r
}
def area(r: Double): Double =
pi * r * r
pi: Double = 3.14 defined function circumference defined function area
If you are viewing this in Jupyter, you may need to enable line numbers (via View > Show Line Numbers
).
Exercise 5.1 The use of pi
at line 4 is bound at which line? Briefly explain.
???
Exercise 5.2 The use of pi
at line 7 is bound at which line? Briefly explain.
???
Consider the following Scala code:
val x = 3
def f(x: Int): Int =
x match {
case 0 => 0
case x => {
val y = x + 1
({
val x = y + 1
y
} * f(x - 1))
}
}
val y = x + f(x)
x: Int = 3 defined function f y: Int = 3
Exercise 5.3 The use of x
at line 3 is bound at which line? Briefly explain.
???
Exercise 5.4 The use of x
at line 6 is bound at which line? Briefly explain.
???
Exercise 5.5 The use of x
at line 10 is bound at which line? Briefly explain.
???
Exercise 5.6 The uses of x
at line 13 is bound at which line? Briefly explain.
???