comprehending comprehensions

Lulu of the Lotus-Eaters mertz at gnosis.cx
Sat Jun 14 16:54:36 EDT 2003


|Roy Smith wrote:
|> Why are list comprehensions called what they are?

Sean 'Shaleh' Perry <shalehperry at attbi.com> wrote
|it came from the functional programing world via ML (or was it Haskell).

Perry's answer is correct, as far as it goes.  But the Haskell/ML usage
itself derives from Zermelo-Frankel axiomatic set theory.  In
particular, the Axiom of Comprehension states: given a set A and a
predicate P, there uniquely exists a set B that contains only elements
of A that fulfill P.

Now backtracking a little, why such an odd axiom? This is because of
Russell's paradox.  Back in the old days, mathematicians thought that
sets were simply the extensionality of intention predicates.  In other
words, given any predicate, sui generis, there is a set of things
fulfilling the predicate.

Russell asked, What about the set of all things that are not members of
themselves?  (It is a member of itself if-and-only-if it is not a
member of itself).  Russell had this awkward solution involving type
hierarchies that is best forgotten.  The more elegant solution is ZFC
axiomatization.  In particular, you avoid the paradox if you need to
start with a prior set A, and only check the predicate against its
members.

So what does this have to do with list comprehensions.  Well, recall how
you would write the set B in math notation.  Subject to the limits of my
keyboard, something like:

    B = {x | x <- A s.t. P(x)}

I try to draw the "member of" symbol as "<-" in ASCII.

Now suppose we turn the usual squiggly set brackets into angle brackets,
and replace "s.t." (such that) with a simple comma:

    [x | x <- A, P(x)]

Viola...  Haskell.  Now suppose we use the word "in" instead of the
ASCII attempt at the member symbol.  And we use the word "if" instead of
"s.t.".  And also, the conditionality mark "|" is expanded to the word
"for":

    [x for x in A if P(x)]

And that's Python.

Yours, Lulu...

--
---[ to our friends at TLAs (spread the word) ]--------------------------
Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego
White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad
---[ Postmodern Enterprises <mertz at gnosis.cx> ]--------------------------






More information about the Python-list mailing list