teaching machines

CS 330 Lecture 26 – List Comprehensions and Map

April 8, 2016 by . Filed under cs330, lectures, spring 2016.

Agenda

TODO

Note

Last time we spent most of the lecture discussing our Program This problem. So, it’s today that we jump into discussing list comprehensions. We start by looking at the template of imperative code that they replace. We introduce the notion of a predicate. We’ll solve a handful of list comprehension problems together.

As we have time, we’ll examine a special case of a list comprehension, one with no predicates and involving only one list. This pattern is called a map, not to be confused with the abstract data type (though the underlying idea of mapping one value to another is the same). We’ll write our own map' function that accepts a transformation function and a list as input.

Code

comprehensions.hs

import Data.List

preditor :: String -> String
preditor s = [pred c | c <- s]

uwecify :: [String] -> [String]
uwecify ids = [id ++ "@uwec.edu" | id <- ids]

addies :: [String]
addies = [col : show row | col <- "ABCD", row <- [0..9]]

pairings :: [String] -> [(String, String)]
pairings items = [(x, y) | x <- items, y <- items, x /= y]

alpha = ['a'..'z']
foowords :: [String]
foowords = [[a, b, c, d, e] | a <- alpha, b <- alpha, c <- alpha, d <- alpha, e <- alpha, "foo" `isInfixOf` [a, b, c, d, e]]