Test 3 Review B: Questions

R3b.1.

In Scala, what is the distinction between a variable declared with var and a variable declared with val?

R3b.2.

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
R3b.3.

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)
R3b.4.

Define the concept of metatable from Lua.

R3b.5.

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

R3b.1.

A variable declared val cannot be changed after its declaration; a var variable can be.

R3b.2.
2
4
5
10
R3b.3.

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 }”.

R3b.4.

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.

R3b.5.
1   3   nil 2   3   nil
4   6   5   4   3   5