Functional Programming in Scala

If/Else

Recursion

Lists

List Functions

Why This Isn't Inefficient

Lab

???

Step 1: If/Else

  1. Open a shell window and type 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.

  2. Type if (true) 3 else "Hello". What do you get? How is it different from the previous result? Why?
  3. Type val num = if (true) 3 else 4. What do you get?
  4. Type val num2 = if (true) 3. What do you get? Why?

Step 2: Recursion

  1. An easy way of computing a power xn (where n is a nonnegative integer) is given by the recursion

    xn = 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?

  2. What is pow(5, 20)?
  3. (If you have extra time) An efficient way of computing a power xn (where n is a nonnegative integer) is given by the recursion

    xn = y2 if n is even and positive, where y = xn / 2

    xn = 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?

Step 3: Lists

  1. What is the type of 1 :: 2 :: 3 :: Nil? (Just ask the Scala interpreter)
  2. What is the type of 1 :: "Hello" :: Nil?
  3. What happens when you evaluate the expression 1 :: 2 :: 3? Why?
  4. How do you make a list of the elements "San", "Jose", "State" using a list constructor? (Be sure to try your answer in the Scala interpreter)
  5. How do you make a list of the elements "San", "Jose", "State" using the cons (::) operator?

Step 4: List Functions

  1. Write a recursive function 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.
  2. What is the result of concat(List("San","Jose"))?
  3. (If you have extra time) How can you modify concat so that it adds spaces between the strings (i.e. so that concat(List("San","Jose")) is "San Jose"?