# teaching machines

## CS 330 Lecture 35 – List Comprehensions and Currying

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

### Agenda

• what ?s
• list comprehensions in Haskell and Scala
• a phobias searcher
• currying
• call-by-name

### 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

• I can generate lists algorithmically using list comprehensions.
• I am familiar with the idea of currying, in which a function of multiple variables is broken down as a composition of several functions accepting a subset of the original parameters.

### Program This

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

• The first 20 powers of 2
• Given a list of integers, an almost-identical list, but whose odd elements have been rounded up to the next even number
• Given a list of lists, the heads of all sublists with lengths greater than three

### 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)
})
}
}