How to parse this line of code manually

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Tue Aug 28 03:59:27 EDT 2007


On 2007-08-28, Davy <zhushenli at gmail.com> wrote:
> On Aug 28, 11:00 am, Davy <zhushe... at gmail.com> wrote:
>> Hi all,
>>
>> It is well known that Python is appreciated for its merit of concise.
>> However, I found the over concise code is too hard to understand for
>> me.
>>
>> Consider, for instance,
>> def known_edits2(word):
>>     return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in
>> NWORDS)
>>
>> Shall I understand the code in set() as
>> for e2 in edits1(e1) {
>>     if e2 in NWORDS {
>>         for e1 in edits1(word) {
>>              e2
>>         }
>>     }
>>
>> }
>>
> [SNIP]
> Hi all, I figured it myself. It is left to righ parse, right?
> So the above one is like
> for e1 in edits1(word) {
>     for e2 in edits1(e1) {
>         if e2 in NWORDS {
>             push e2 to set
>         }
>     }
> }

This is correct, although I am not sure what language you are using here, it
looks like a strange mix of Python and C to me.

>> Any suggestions are welcome!

The idea is known as List comprehension (for lists, obviously), and comes from
functional programming, Bird & Wadler used it in their book.



The notation is very close to mathematics:

 { e2 | e1: edits(word), e2: edits(e1) in NWORDS } 

or in LaTeX:

$\{ e_2 | \forall e_1: \mathrm{edits}(\mathrm{words}),
          \forall e_2: \mathrm{edits}(e_1) \in \mathrm{NWORDS} \}$

:-)

(which in words is something like: collect values e2, where e1 comes from
'edits(word)', e2 comes from 'edits(e1)', and e2 in NWORDS)


Sincerely,
Albert



More information about the Python-list mailing list