More About Closures

Type Inference

Type Inference 2

Parameter Inference From Context

Parameter Simplifications

Control Abstractions

By-Name Parameters

Currying

The While Control Abstraction

A Useful Control Abstraction

Lab

???

Step 1: Short Function Notation

  1. What is the shortest command you can use to

    For each of these, first store the list in a variable lst

    val lst = List("Alpha", "Bravo", "Charlie", "Delta")

Step 2: Currying

  1. Here is a function of computing the “maximum” string in a list that works for any ordering.
    def max(lst : List[String], less : (String, String) => Boolean) =
      (lst.head /: lst.tail)((x, y) => if (less(x, y)) y else x)

    Make a call to max that yields the longest string in a list lst. Use _ for the string parameters in your less function.

  2. Now we'll make this generic. Don't worry—it won't hurt a bit:
    def max[T](lst : List[T], less : (T, T) => Boolean) =
      (lst.head /: lst.tail)((x, y) => if (less(x, y)) y else x)

    What happens when you call max(lst, _ < _)?

  3. Ok, that didn't work so well. Currying to the rescue. Curry the max[T] function, exactly like mul2 above. What is the code for your revised function? What happens when you call max2(lst)(_ < _)?

    (Why does this work? Now the Scala type inferencer knows that T must be String after processing max2(lst).)

Step 3: Implement DoWrite

  1. Implement the DoWrite control abstraction from the lecture. The While example isn't a perfect model to follow:

    What is the type of that function?

  2. Using Currying, define DoWrite(writer : PrintWriter)(body: the type you deduced in step 1). Make a try/finally block. In the inside of the try, simply call body.
  3. Call
    DoWrite(new PrintWriter("abc.txt")) { writer => 
      writer.println("Alpha")
      writer.println("Bravo")
      writer.println("Charlie")
    }

    Where is the file abc.txt located, and what is its contents?

Step 4: Checking DoWrite

  1. We want to see that the DoWrite abstraction does its job. Call
    def test() {
      val writer = new PrintWriter("def.txt")
      writer.println("Delta")
      writer.println("Echo")
      throw new NullPointerException()
      writer.println("Foxtrot")
    }

    What happens?

  2. What is in def.txt? What did you expect to be in it?
  3. Now call
    DoWrite(new PrintWriter("def.txt")) { writer => 
      writer.println("Delta");
      throw new NullPointerException()
      writer.println("Foxtrot");
    }

    What is in def.txt? What does that prove?