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 = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers.map((x : Int) => x * x)
// Yields a new List(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
map
function in Java that does the same?public static <T> List<R> map(List<T> values, Transformer<T, R> f)
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
42.toHexString
()
"Hello".toUpper
doesn't change "Hello"
but returns a new string "HELLO"
val
are immutable
val num = 3.14 num = 1.42 // Error
if (booleanExpression) expression1 else expression2
val x = (if (true) 2 else 4) * 3
? :
in Javaval x = if (true) 3 else "Hello" // type is AnyVal
else
yields type Unit
(like void
in Java); not useful in functional programmingdef
syntax for functions
def triple(x : Int) = 3 * x // same as val triple = (x : Int) => 3 * x
def fac(x : Int) : Int = if (x == 0) 1 else x * fac(x - 1)
def
because the name is used on the right
val fac = (x : Int) => if (x == 0) 1 else x * fac(x - 1) // fac not defined yet
while
, for
) can always be expressed as recursion
lab1/report.txt
inside the Git repo. Include the coder's name in the report!lab1
and click Finish. Right-click on the project in the Package Explorer, then select New -> Scala worksheet. Call it sheet1
.39+3
and save the worksheet. What do you get?val a = 39 + 3
. What do you get?a + 1
. What do you get? a = 9
. 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?
HINT: These “What do you get” exercises are a lot more effective when you and your buddy first discuss what you think you'll get. “Form a hypothesis” is an essential part of the learning path.
triple
. What do you get?triple
in Scala?5
in Scala?List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
. What do you get?List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).map(triple)
. What do you get? Why? val
or def
? Hint: Anonymous function.sevens(n: Int): Int
that counts how many digits of n
are the digit 7. For example, sevens(747)
returns 2. How would you do this in Java (without converting the number to a string)?n
is 0, you know the answer. Otherwise, in plain English or pseudocode, how can you compute the answer from n % 10
and sevens(n / 10)
?