if (booleanExpression) expression1 else expression2
val x = (if (true) 2 else 4) * 3
? : in Javaval x = if (true) 3 else 3.14 // 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 = if (x == 0) 1 else x * fac(x - 1) // fac not defined yet
while, for) can always be expressed
as recursion
To iterate is human; to recurse, divine (L. Peter Deutsch)
::)Nil) or has a head and tail
val lst = List(1, 4, 9) lst.head // 1 lst.tail // List(4, 9) lst.tail.tail.tail // Nil
:: to build lists
0 :: lst // List(0, 1, 4, 9)
def sum(lst : List[Int]) : Int =
if (lst.isEmpty)
0 else // NOTE: else must be on this line
lst.head + sum(lst.tail)
:: to recursively build lists
def squares(n : Int) : List[Int] =
if (n == 0)
List(0) else
n * n :: squares(n - 1)
lst.tail doesn't make a new list—it is a reference to
the tail cell


scala. Type if (true) 3
else 4. As always, don't type the period, but type ENTER. What do
you get?
HINT: These “What do you get” exercises are a lot more effective when you and your buddy first discuss whar you think you'll get. “Form a hypothesis” is an essential part of the learning path.
if (true) 3 else "Hello". What do you get? How is it
different from the previous result? Why?val num = if (true) 3 else 4. What do you get? val num2 = if (true) 3. What do you get? Why? xn = x· xn - 1 if n > 0
x0 = 1
Write a Scala function pow(x : Double, n : Int) : Double
that implements this algorithm. What is the code of your function?
pow(5, 20)?xn = y2 if n is even and positive, where y = xn / 2
xn = x· xn - 1 if n is odd
x0 = 1
Write a Scala function pow(x : Double, n : Int) : Int that
implements this algorithm. What is the code of your function?
1 :: 2 :: 3 :: Nil? (Just ask the Scala
interpreter)1 :: "Hello" :: Nil?1 :: 2 :: 3?
Why?"San",
"Jose", "State" using a list constructor? (Be
sure to try your answer in the Scala interpreter)"San",
"Jose", "State" using the cons (::)
operator? concat that concatenates all
strings in a List[String], yielding a String.
Hint: concat(Nil) is "". What is
concat(lst) in terms if lst.head,
lst.tail? Give the code of your function. concat(List("San","Jose"))?concat so that
it adds spaces between the strings (i.e. so that
concat(List("San","Jose")) is "San Jose"?