# list comprehensions *are* nice

Hannah Schroeter hannah at schlund.de
Tue May 15 10:32:33 EDT 2001

```Hello!

In article <9dqd05\$bp4 at gap.cco.caltech.edu>,
Nathan Gray <n8gray at caltech.edu.is.my.e-mail.address> wrote:

>[...]

>def qsort(lst):
>    if len(lst) <= 1: return lst
>    return qsort([lessthan for lessthan in lst[1:] if lessthan < lst]) +
>\
>            [lst] + qsort([grtreq for grtreq in lst[1:] if grtreq >=
>lst])

qsort lst =
if length lst <= 1
then lst
else qsort [lessthan | lessthan <- tail lst, lessthan < head lst]
++ qsort [grtreq | grtreq <- tail lst, grtreq >= head lst]

Now some CSE on "head lst", "tail lst"

qsort lst =
if length lst <= 1
then lst
else qsort [lessthan | lessthan <- tl, lessthan < hd]
++ [hd]
++ qsort [grtreq | grtreq <- tl, grtreq >= hd]
where
tl = tail lst

Now do it with more than one equation and pattern matching:

qsort lst | length lst <= 1 = lst
qsort (hd:tl) =
qsort [lessthan | lessthan <- tl, lessthan < hd]
++ [hd]
++ qsort [grtreq | grtreq <- tl, grtreq >= hd]

Now, [x] ++ foo === x:foo, which is a bit more efficient, thus

qsort lst | length lst <= 1 = lst
qsort (hd:tl) =
qsort [lessthan | lessthan <- tl, lessthan < hd]
++ hd : qsort [grtreq | grtreq <- tl, grtreq >= hd]

facit: people accustomed to Haskell *might* miss pattern matching/
multiple heads for the same functions/function guards a bit in Python.

Kind regards,

Hannah.

```