jashkenas/coffee-script — Issue #2039: documenting comprehensions
Author: showell
Created: 2012-01-14 17:38:32+00:00
State: open

There are a couple open issues on nested comprehensions, where folks ask whether CoffeeScript should be more like Python and Haskell. However those issues get resolved, we can probably start by documenting the current behavior more precisely.

First, without getting into abstract definitions, it's pretty easy to call out the two main differences between CoffeeScript and Python:

1. Nested comprehensions are not automatically flattened (map instead of concatMap/flatMap)
1. The index of the comprehension nested deepest varies fastest

Second, it's important to call out the distinction between these lines in coffeescript:

```
eat(x) for x in a # loop w/side effects
squares = (square(x) for x in a) # comprehension
```

Third, it's important to distinguish these two syntactical constructs (which produce the same code):

```
squares = (square(x) for x in a) # comprehension
```

```
squares = (for x in a
square(x)) # array expression
```
The two pieces of code are identical semantically, but they are different syntactically. IMHO we should use a precise definition of "comprehension" that refers specifically to the first syntax. Wikipedia and Python's PEP both provide precedence for calling out comprehensions as a specific syntactical notation for producing lists. Wikipedia emphasizes the analogy to set builder notation, which specifically puts the output function first in the expression.

I propose these definitions:

1. Loops - classic loops used to produce side effects
1. Postfix loops -- classic loops where the one-statement body goes first
1. List expressions -- loops in CS that are evaluated as expressions, where "for" precedes the body
1. Comprehensions -- syntax in CS that specifically places the output expression before the "for"

I predict these definitions will be up for extensive debate. See the discussion between me and @michaelficarra at [issue 2030](https://github.com/jashkenas/coffee-script/issues/2030).

Once the definitions get nailed down, I propose that we reorganize the docs to show all four forms separately, even if we can't agree to come up with four different terms for the forms.

Other related issues:

1. [issue 1191](https://github.com/jashkenas/coffee-script/issues/1191)
1. [issue 2038](https://github.com/jashkenas/coffee-script/issues/2038)