CS 152 - Lecture 5

Cover page image

Cay S. Horstmann

Higher Order Functions

Producing Functions

Producing Functions

Comparators

Composing Comparators

Composing Comparators

Currying

Lab

???

Step 1: Short Function Notation

Define a variable lst as

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

What is the shortest command you can use to

  1. Yield all short strings (of length < 5) from lst
  2. Yield the words sorted by increasing length
  3. Find the longest string (using reduce)

Step 2: Currying

Step 3: More 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.reduce((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 make this generic. Don't worry—it won't hurt a bit:
    def max[T](lst : List[T], less : (T, T) => Boolean) =
      lst.reduce((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 multiply above. What is the code for your revised function? What happens when you call max(lst)(_ < _)?

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