CS 152 - Lecture 2

Cover page image

Cay S. Horstmann

Functional Programming

Functional Programming in Scala

Why Functional Programming?

Scala Basics

Immutability

If/Else

Recursion

Lab

???

Step 1: The Scala Interpreter

  1. Start Eclipse and make a new Scala project: File -> New -> Project -> Scala Project. Give a name lab1 and click Finish. Right-click on the project in the Package Explorer, then select New -> Scala worksheet. Call it sheet1.
  2. Type 39+3 and save the worksheet. What do you get?
  3. Type val a = 39 + 3. What do you get?
  4. Type a + 1. What do you get?
  5. Type a = 9. What do you get? Why?
  6. Type val b; (This time with a semicolon.) What do you get? Why?

Step 2: Functions are Values

  1. Type val triple = (x : Int) => 3 * x. What do you get?
  2. Type 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.

  3. Type triple. What do you get?
  4. What is the type of triple in Scala?
  5. What is the type of 5 in Scala?

Step 3: Functions as Parameters

  1. Type List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10). What do you get?
  2. Type List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).map(triple). What do you get? Why?
  3. How do you get the cubes of the numbers from 1 to 10 without using val or def? Hint: Anonymous function.

Step 4: Simple Recursion

  1. Your task is to write a 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)?
  2. In functional programming, you can't increment a counter. But you can use recursion. How can you compute the answer recursively? Hint: If 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)?
  3. What's your code in Scala?