Closures

Functions as Parameters

Capturing the Enclosing Environment

Application: Event Handling

Lab

???

Step 1: Filters

  1. What does the following function do? If in doubt, call it with a few values.
    val isEven = (x : Int) => x % 2 == 0
  2. Type (1 to 10).filter(isEven). 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.

  3. Describe what filter does.

Step 2: A Random Number List

  1. The random number generator in Scala is similar to that in Java. What output do you get from
    val gen = new Random
    gen.nextInt(10)
    gen.nextInt(10)
  2. What is the significance of the 10?
  3. We want to define a function randList(len : Int, n : Int) : List[Int] that makes a list of length len of random integers between 0 and n - 1. For example, randList(5, 10) might yield a list of numbers 5 1 2 0 9. Define randList as a recursive function. What is the code of your function?

    Hint: If len is 0, the result is nil. Otherwise, it is gen.nextInt(n) :: something. What is your definition?

    Note: You need not define gen. You already defined it in part 1. Just use it.

  4. What do you get for randList(5, 1000)? For randList(1000, 5)?
  5. Why is randList a closure?

Step 3: Filtering Large Numbers

  1. Write a function greaterThan100(lst : List[Int]) that returns only those integers in lst that are greater than 100. Don't use recursion; simply call filter with an appropriate function:
    def greaterThan100(lst : List[Int]) = {
      val fun = ... // your work 
      lst.filter(fun) // NOTE: The last expression in a { ... } is its value
    }

    What is your function's code?

  2. What is the value of greaterThan100(randList(10, 200))? Why does that give you confidence that you implemented everything correctly?
  3. Of course, having a hard-wired bound of 100 is intensely ugly. Let's generalize:
    def greaterThan(n : Int, lst : List[Int]) = {
      val fun = ... // your work 
      lst.filter(fun) 
    }

    For example, greaterThan(50, nums) yields all values of nums > 50.

    What is the code of your greaterThan function?

  4. What is the value of greaterThan(100, randList(10, 200))?
  5. Why is the fun inside greaterThan a closure?

Step 4: Listeners (Optional)

Do this if you have extra time.

  1. Run the listener example code, by pasting the instructions from action.scala into your Scala interpreter. (This is probably an exercise in frustration if you use the Windows shell. Remedy: rxvt in Bash or emacs.) What happens if you click each of the buttons?
  2. Fix the Exit button so that it calls frame.setVisible(false). How did you do that?