
Copyright © Cay S. Horstmann 2015 
This work is licensed under a Creative Commons Attribution 4.0 International License

...that HEIG-VD computer science graduates wish they had learned better in college?
Int, Double, Boolean, String+ - * / %val luckyNumber = 13 // luckyNumber is an Int
val square = (x: Int) => x * x // square is an Int => Int
val x = 1 val y = 2 + // end line with operator to indicate that there is more to come 3
1.to(10) // Apply to method to 1, returns Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
1.to(10) yields a RangeList, Vector (similar to C++), Range, many moremap works on any collection
val square = (x: Int) => x * x 1.to(9).map(square) // Yields 1 4 9 16 25 ... 81
1.to(9).map(square).map(x => x % 10).distinct
() behind distinct. Rule of thumb: no args and not mutating ⇒ no ()int, double, etc.val num = 3.14 val fun = math.ceil _ fun(num) // prints 4
(x: Int) => x * x
3.14
val square = (x: Int) => x * x square(10) // prints 100
val pi = 3.14 pi * 10 // prints 31.4
val numbers = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers.map((x: Int) => x * x) // Prints Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
vector<int> map(vector<int> values, int (*f)(int)) {
vector<int> result;
for (int i = 0; i < size; i++) result.push_back(f(values[i]));
return result;
}
int square(int x) { return x * x; }
...
res = map(numbers, square); // Must pass name of function
"Hello".toUpper() doesn't change "Hello" but returns a new string "HELLO"val are immutable
val num = 3.14 num = 1.42 // Error

Worksheets. Right-click on the project in the Package Explorer, then select New -> Scala Worksheet. Call it Day1.} . Type 6 * 7 and then save (Ctrl+S/⌘+S). What do you get?val a = 6 * 7 and save. What do you get?a. What do you get? a = 43. What do you get? Why?val b; (This time with a semicolon.) What do you get? Why?val triple = (x: Int) => 3 * x. What do you get? triple(5). What do you get?
Tip: These “What do you get” exercises are a lot more enjoyable and effective when you and your buddy first discuss what you think you'll get before you execute the Save command.
triple. What do you get?triple in Scala?5 in Scala?1.to(10). What do you get?1.to(10).map(triple). What do you get? Why? val? Hint: Anonymous functionsDo you remember this?
0.to(9).map(square).map(x => x % 10).distinct
Try it out. What did you get?
n? Write a function val qres = (n: Int) => ... that produces them. What is your function? What is qres(20)?n going from 2 to 20, how many quadratic residues are there?
Hint: 2.to(20).map(...) and map(l -> l.length)