Test 3 Review B: Questions
In Scala, what is the distinction between a variable declared
with var
and a variable declared with val
?
Given the following Scala function definition, what is the output of
mystery(100)
?
def mystery(n: Int) = (2 until n) takeWhile (i => i * i <= n) filter (n % _ == 0) map println
The following Scala program spawns 10 actors to count the number of
primes in different ranges of integers. Complete the program below so
that each actor sends its result to caller
to add the
results together.
import scala.actors._
-- definition of countPrimes omitted
val num_actors: Int = 10
val caller = Actor.self
for (i <- 0 until num_actors) {
Actor.actor {
val k = countPrimes(i * 1000000 / num_actors, (i + 1) * 1000000 / num_actors)
// TODO: Send message to "caller" including "k" result
}
}
var total: Int = 0
for (i <- 0 until num_actors) {
// TODO: Receive a single actor's message and add it into total
}
println("Total found is " + total)
Define the concept of metatable from Lua.
What is the output of the following Lua code fragment? (When retrieving the
value associated with a key absent from a table, the Lua interpreter returns
nil
.)
a = {}
b = {}
b.__index = b
setmetatable(a, b)
a.i = 1
b.i = 2
b.j = 3
print(a.i, a.j, a.k, b.i, b.j, b.k)
b.i = 4
b.k = 5
a.i = nil -- deletes the key "i" from "a"
a.j = 6
print(a.i, a.j, a.k, b.i, b.j, b.k)
Test 3 Review B: Solutions
A variable declared val
cannot be changed after its
declaration; a var
variable can be.
2
4
5
10
In place of the first TODO
comment (in the first loop), write
“caller ! k
”
In place of the second TODO
comment (in the second loop),
write
“Actor.receive { case found: Int => total += found }
”.
Every table T has at most one associated table, its metatable.
When a key is looked up within T but the key isn't represented
in T, the interpreter then looks within T's metatable
for an __index
value giving a backup method for retrieving the key.
1 3 nil 2 3 nil
4 6 5 4 3 5