comprehending comprehensions

Bengt Richter bokr at oz.net
Sat Jun 14 20:49:39 EDT 2003


On Sat, 14 Jun 2003 22:46:55 GMT, Maurix <maurix78_remove_this_ at wanadoo.es> wrote:

>Hi, as you are speaking of comprehensions, functional languages
>and Haskell; i want to propose a game to the group:
>Let's make some examples to see how long is python compared
>with Haskell.
>I've make my try, writing the famous example of qsort in Haskell
>in a "functional" python:
>
>Haskell:
>
>qsort []     = []
>qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x
>		 where
>		   elts_lt_x   = [y | y <- xs, y < x]
>		   elts_greq_x = [y | y <- xs, y >= x]
>
>
>Python:
>
>def qsort(list) :
>    if len(list)<=1 : return list
>    x,xs=list[0],list[1:]
>    elts_lt_x=[y for y in xs if y < x]
>    elts_greq_x=[y for y in xs if y >= x]
>    return qsort(elts_lt_x)+[x]+qsort(elts_greq_x)
>
>6 lines vs 5 lines, not bad!
>Someting can do it better??
You can take a line out by taking advantage of short circuit logic and
the fact that list.append returns None:
(it breaks the lookalike pattern though ;-)

def qsort(seq) :  # practically untested
    if len(seq)<=1 : return seq
    x,xs,elts_greq_x = seq[0],seq[1:],[]
    elts_lt_x=[y for y in xs if y < x or elts_greq_x.append(y)] #(append => None)
    return qsort(elts_lt_x)+[x]+qsort(elts_greq_x)

BTW, 'list' is a builtin, so it's not a good choice for a parameter name.
>
>I have a question too, there something in haskell that is
>difficult to "copy" with python?
>
>I like haskell for his math-style but have really something more?
Haskell and ML (OCAML?) are both round tuits as yet for me.
Which is tastiest?

Regards,
Bengt Richter




More information about the Python-list mailing list