list comprehensions *are* nice

Hannah Schroeter hannah at schlund.de
Tue May 15 16:32:33 CEST 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[0]]) +
>\
>            [lst[0]] + qsort([grtreq for grtreq in lst[1:] if grtreq >=
>lst[0]])

>Take that, Haskell!  List comprehensions are rad.

Literal translation to Haskell:

qsort lst =
  if length lst <= 1
  then lst
  else qsort [lessthan | lessthan <- tail lst, lessthan < head lst]
    ++ [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
  hd = head lst
  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.



More information about the Python-list mailing list