CS 152 - Lecture 3

Cover page image

Cay S. Horstmann

Blocks

Local Functions

Lists

List Functions

Why This Isn't Inefficient

More Recursion Examples

Lab

???

Step 1: 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", "José", "State", "University" 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", "José", "State", "University" using the cons (::) operator?

Step 2: List Functions

  1. Write a recursive function concat that concatenates all strings in a List[String], yielding a String. Hint: (1) String concatenation is + in Scala, just like in Java (2) concat(Nil) is "". (3) Think about concat(lst) in terms of lst.head, lst.tail.

    Give the code of your function.

  2. What is the result of concat(List("San", "José", "State", "University"))?
  3. How can you modify concat so that it adds spaces between the strings (i.e. so that concat(List("San", "José", "State", "University")) is "San José State University" but not "San José State University " or " San José State University"?

Step 3: More Recursion

  1. Given a list, form a list of all pairs of elements (as lists of length 2) in some order. If the original list has length n, form n2 pairs. What should pairs(List(1, 2, 3)) produce?
  2. What is your strategy for recursion? Base case? Reduction to simpler case?
  3. What is your Scala code?

Step 4: Not Always Recursion

  1. How can you implement the squares function from the lecture without recursion?
  2. The flatten method flattens out a list of lists into a list. To see what it does, just try out
    List(List(1, 2),List(3, 4, 5)).flatten
    Assuming that you are allowed to use this method, how can you implement the pairs function of Step 3 without recursion?