# More on Lists # ## Comprehensions ## We know you are already familiar with the following kind of notation for designating sets: { x + 1 | x ∈ Primes and φx } This kind of notation is called a **set comprehension.** Here Primes is assumed to be some, presumably larger set. φ expresses some condition that members of Primes might conceivably fail to satisfy. Some of the functional programming languages permit you to specify data structures in this same way. Kapulet comes closest, in that it also has set comprehension notation. In Kaupulet one writes: { x + 1 | x from Primes, φ x } The changes are only that we write `x from Primes`, with `Primes` being an expression that evaluates to a set, and we separate that clause from the test clause with a comma. φ x can be any expression that evaluates to a boolean. Moreover, such clauses can come in any order, and there can be any number of them, though the above is the most useful pattern. But you can also write: { 1 | 'true } which evaluates to `{ 1 }`, or: { 1 | 'false } which evaluates to the empty set `{ }`. What if you have multiple `from` clauses? This is possible, and iterates over the *cross-product* of the two sets you're drawing from. So: { 10*x + y | x from {1, 2, 3}, y from {4, 5} } evaluates to the set `{ 14, 15, 24, 25, 34, 35 }`. Haskell doesn't have set literals like Kapulet does, but it also allows this kind of notation with lists, that is, it has **list comprehensions**. (And so does Kapulet.) Thus in Haskell you can write: [ 10*x + y | x <- [1, 2, 3], y <- [4, 5] ] and that evaluates to `[14, 15, 24, 25, 34, 35]`. Notice that Haskell's syntax differs slightly. Changing the order of the `from`/`<-` clauses changes the order in which the elements will be added to the result list: [ 10*x + y | y <- [4, 5], x <- [1, 2, 3] ] That evaluates to `[14, 24, 34, 15, 25, 35]`. You can also mix in test clauses: [ 10*x + y | y <- [4, 5], odd y, x <- [1, 2, 3] ] evaluates to `[15, 25, 35]`. Haskell also has an extension that permits you to iterate over multiple lists *in parallel* rather than to iterate over their cross-product. If you type `:set -XParallelListComp` in the ghci interpreter, that will enable this extension, and then: [ 10*x + y | y <- [4, 5, 6] | x <- [1, 2, 3] ] will evaluate to `[14, 25, 36]`. If the lists are of unequal length, Haskell stops when it exhausts the shortest. These behaviors are similar to the `map2` function you defined in the week 1 homework. That also took an argument from each of several sequences in parallel. (The corresponding functions in Haskell are called `zip` and `zipWith`.) OCaml [permits lists comprehensions as an extension](http://stackoverflow.com/questions/27652428/list-comprehension-in-ocaml), and [so too does Scheme](http://srfi.schemers.org/srfi-42/srfi-42.html), but these are a bit harder to use. All of these things can also be expressed in these languages without using the comprehension syntax. For example, this list comprehension (in Kapulet syntax): [ 10*x | x from [1, 2, 3, 4, 5] ] can be expressed as: map (lambda x. 10*x) [1, 2, 3, 4, 5] and this: [ 10*x | x from [1, 2, 3, 4, 5], odd? x ] can be expressed as: map (lambda x. 10*x) $ filter odd? [1, 2, 3, 4, 5] (We explained the `$` notation in [[week 1's advanced notes|week1_kapulet_advanced/#dollar]]. This is equivalent to `map (lambda x. 10*x) (filter odd? [1, 2, 3, 4, 5])`.) Iterating over the cross-product of several lists is a bit harder. Consider: [ 10*x + y | y from [4, 5, 6], y < 6, x from [1, 2, 3] ] To translate that, first let's handle the iteration over the final list, that `x` is drawn from: map (lambda x. 10*x + y) [1, 2, 3] This looks like what we had before, except that now we have this free variable `y` in our lambda expression. Perhaps we can bind that variable inside a *larger* lambda expression, and then map (and filter) *that* larger lambda expression over the list that `y` is drawn from: let f match lambda y. map (lambda x. 10*x + y) [1, 2, 3] in map f $ filter (lambda y. y < 6) [4, 5, 6] This gives us nearly what we want. It evaluates to: [[14, 24, 34], [15, 25, 35]] Why? Because the `filter` expression at the end is restricting the domain that `y` ranges over to `[4, 5]`. Over this domain we are selecting a value to bind `y` to, and then evaluating the `map` expression inside `f` with `y` so bound. With `y` bound to `4`, we get the result `[14, 24, 34]`. With `y` bound to `5`, we get the result `[15, 25, 35]`. These two results, in order, are the elements that make up the sequence which is the result of the outermost `map` expression. One final twist is that our original list comprehension gives us a "flatter" result. In both Kapulet (and Haskell, modulo a few syntax adjustments), the list comprehension: [ 10*x + y | y from [4, 5, 6], y < 6, x from [1, 2, 3] ] evaluates to: [14, 24, 34, 15, 25, 35] We can turn the preceding result into this result with the Kapulet function `join` (Haskell calls it `concat` or `Control.Monad.join`): join [[14, 24, 34], [15, 25, 35]] evaluates to the "flatter" list displayed above. By the way, this `join` operation only affects a single layer of `[ ]`s. This: join [ [[10,20], [30], []], [[40], [50,60]] ] evaluates to: [[10,20], [30], [], [40], [50,60]] not to: [10, 20, 30, 40, 50, 60] To get the latter, you'd need to apply `join` twice. ## Tails ## For the Lambda Calculus, we've proposed to encode lists in terms of higher-order functions that perform right-folds on (what we intuitively regard as) the real list. Thus, the list we'd write in Kapulet or Haskell as: [a, b, c] for some expressions `a`, `b`, and `c`, would be encoded in the Lambda Calculus as: \f z. f a (f b (f c z)) With that choice of encoding, it's not difficult to write a `head` function. You did this for one of the week 2 homeworks. However, it is more challenging to write a `tail` function. Here is the intuitive idea behind one way we could do this. Our "starting value" --- what gets bound to `z` in the above lambda expression --- will be *a pair* of two values. I'll write it as `([], err)` for the moment, while we fix our intuitions, rather than using the more verbose Lambda Calculus representation of pairs and `[]`. The `err` will be whatever we decide should be the `tail` of an empty list. Perhaps it should be `[]`, but I'll just leave it as `err` for this exercise. Now, when we combine the rightmost element of the list with this, by evaluating `f c ([], err)`, we want the result to be `([c], [])`. That is, we throw away the second member of the pair, copy the first member over into the second slot, and `cons` the `c` onto the first member in the first slot. At the next stage, the result will be `([b, c], [c])`. And at the final stage, the result will be `([a, b, c], [b, c])`. Now we just have to extract the second member of this pair, and that will be the tail of our list. If you've followed that intuitive presentation, then here is how you can write it in the lambda evaluator: let empty = \f z. z in ; as before let cons = \d ds. \f z. f d (ds f z) in ; as before let pair = \x y. \f. f x y in let snd = \x y. y in let shift = \h p. p (\x y. pair (cons h x) x) in let tail = \xs. (xs shift (pair empty err)) snd in ... Here `shift` is our fold-function, and takes two arguments, the current list element `h` and the pair `p` that we've built up from the starting value by folding over the more rightward portion of the list, if any. The `shift` function binds the two members of the pair to `x` and `y`, disregarding the second. It returns a new pair whose first member is `cons h x` and whose second member is `x`. Our starting value is `pair empty err`. And at the end of our fold we're left with a pair, and want to extract its second member; that's why `tail` is of the form `\xs. (xs shift ...) snd`. Try it out in the lambda evaluator. After the code above, you can write: ... let abc = cons a (cons b (cons c empty)) in ; encoding of [a, b, c] tail abc and the result will be `\f z. f b (f c z)`, our encoding of `[b, c]`.