teaching machines

CS 330 Lecture 35 – List Comprehensions and Currying

May 1, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

Puzzle

On Friday, May 1, the Federal Aviation Administration issued a warning about a bug in Boeing’s 787 Dreamliner aircraft. If all four of the machine’s generator control units run continuously for 248 consecutive days, the electrical system will shutdown. The law of leaky abstractions strikes again. Why 248 days?

Intentions

Program This

Generate the following lists in two ways: using a list comprehension and in a functional style:

Code

Listing.scala

import scala.math._

object Listing {
  def main(args: Array[String]) {
    val powers = (1 to 20).map(x => pow(2, x))
    println(powers)

    val powers2 = for (x <- 1 to 20) yield pow(2, x)
    println(powers2)

    val foo = for (x <- 1 to 3; y <- 10 to 11) yield x + y
    println(foo)
  }
}

Phobias.scala

import scala.collection.mutable.HashMap
import java.util.Scanner
import scala.io.Source

object Phobias {
  def main(args: Array[String]) {
    val phobiasSearcher = lookup(args(0))

    // do the stuff
    val in = new Scanner(System.in)
    print("? ")
    while (in.hasNextLine) {
      val line = in.nextLine
      val matches = phobiasSearcher(line)
      for ((key, value) <- matches) {
        println(key + ": " + value)
      }
      print("? ")
    }
  }

  def lookup(path: String) = {
    val pairs = Source.fromFile(path).getLines.map(line => {
      val fields = line.split(" - ", 2)
      (fields(0), fields(1))
    })

    val dictionary = pairs.foldLeft(new HashMap[String, String])((dictionary, keyValuePair) => {
      dictionary += keyValuePair
    })
    println("got a hashmap")

    (keyword : String) => dictionary.filter(keyValuePair => {
      keyValuePair._2.toLowerCase.contains(keyword.toLowerCase)
    })
  }
}