| CIS 554 -- Scala
Quiz 1 |
Name
__________________________________
|
Please do not provide more than the question asks for. If I ask for a statement, don't put it in a function. If I ask for a function, don't put it in a class. If I ask to compute a value, don't print the result. And so on. I may or may not, at my discretion, mark such unnecessarily verbose answers as wrong.
- (1 point) Define numbers to be an immutable List of the integers 1 to 200, inclusive. Do not use a loop or recursion.
val numbers = (1 to 200) toList
- (1 point) Define an immutable List someNums containing those numbers in numbers (from the previous question) that are either evenly divisible by 7, or whose last (rightmost) digit is a 3, or both. Do this with a filter, not with a loop or recursion.
val someNums = numbers filter(x => x % 7 == 0 || x % 10 == 3)
- (1 point) Use a for-comprehension to define an immutable List someSquares containing the squares of the numbers in someNums (from the previous question).
val someSquares = for (x <- someNums) yield x * x
another popular correct answer was:
val someSquares = for (i <- 0 until someNums.length) yield someNums(i) * someNums(i)
- (1 point) Tell what the result will be of each of the following function calls:
- List(30, 75, 40, 85) find (_ > 50)
Some(75)
- List(30, 75, 40, 85) find (_ > 90)
None
- (1 point) Here is a complete class definition:
class Noun(val text: String, var suffix: String, singular: Boolean)
List the names of all the getters and setters
that Scala automatically provides for objects of this class.
Getters: text, suffix
Setter: suffix_= (Popular wrong answers: suffix_, _suffix, suffix())
- (1 point) Write a match statement that uses the find function to find the first value in the list myList that is larger than 500, and either prints the value that was found, or prints "No such number."
myList.find (_ > 500) match {
case Some(x) => println(x)
case None => println("No such number.")
}
- (3 points) Define:
- Referential transparency
The ability to replace a computation with the result of the computation, without changing the behavior of a program (except possibly to make it more efficient). Said of pure functions.
- Uniform access principle
The ability to get a value without having to know whether it is stored in a variable or being computed by a function.
- (1 point) Given two lists of integers, list1 and list2, create a list of sums of the corresponding elements. For example, if list1 = List(10, 20, 30) and list2 = List(1, 2, 3, 4), produce the list List(11, 22, 33). You may use a for-comprehension, but no other kind of loop or recursion.
for (n <- list1 zip list2) yield n._1 + n._2
Most popular wrong answer: for {x <- list1; y <- list2} yield x + y
- (1 point) What is printed by the following sequence of expressions?
var x = 3
val y = 5
val foo = (z: Int) => {
val y = 11
x + y + z
}
x = 10
println(foo(y))
Correct answer: 26
Most popular wrong answer: 19
(This is a question about closures.)