473,841 Members | 1,837 Online

# can Python be useful as functional?

Hi all,
I haven't experienced functional programming very much, but now I'm
trying to learn Haskell and I've learned that: 1) in functional
programming LISTS are fundmental; 2) any "cycle" in FP become
recursion.
I also know that Python got some useful tool such as map, filter,
reduce... so I told: "let's try some FP-style programming with
Python!". I took a little example of Haskell:

listprimes :: Integer -[Integer]
listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)]
where
sieve [] = []
sieve (p:xs) = p : sieve (filter (\x -mod x p 0) xs)

and I tried to "translate" it in Python:

def sieve(s):
if s == []:
return []
else:
return [s[0]] + sieve(filter((l ambda x: x % s[0] 0),
s[1:]))

def listprimes(n):
return sieve(range(2,n ))

These should be almost the same: listprimes actually lists prime
integers up to n-1. The result is: Haskell implementation works well,
maybe it's not the better way to do it, but it does what I wanted.
Python implementation gives me

RuntimeError: maximum recursion depth exceeded in cmp

My question is: how can we call a language "functional " if it's major
implementation has a limited stack? Or is my code wrong?

LS

Sep 17 '07 #1
15 1737
On 9/17/07, Lorenzo Stella <lo******@gmail .comwrote:
Hi all,
I haven't experienced functional programming very much, but now I'm
trying to learn Haskell and I've learned that: 1) in functional
programming LISTS are fundmental; 2) any "cycle" in FP become
recursion.
I also know that Python got some useful tool such as map, filter,
reduce... so I told: "let's try some FP-style programming with
Python!". I took a little example of Haskell:

listprimes :: Integer -[Integer]
listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)]
where
sieve [] = []
sieve (p:xs) = p : sieve (filter (\x -mod x p 0) xs)

and I tried to "translate" it in Python:

def sieve(s):
if s == []:
return []
else:
return [s[0]] + sieve(filter((l ambda x: x % s[0] 0),
s[1:]))

def listprimes(n):
return sieve(range(2,n ))

These should be almost the same: listprimes actually lists prime
integers up to n-1. The result is: Haskell implementation works well,
maybe it's not the better way to do it, but it does what I wanted.
Python implementation gives me

RuntimeError: maximum recursion depth exceeded in cmp

My question is: how can we call a language "functional " if it's major
implementation has a limited stack? Or is my code wrong?
Python does not optimize tail recursion. You can increase the maximum
recursion limit with sys.setrecursio nlimit, but the code will still be
slow.

I am a fan of functional programming languages (including Haskell!),
but I wouldn't try to write functional code in Python -- the language
isn't optimized for this type of code, and the syntax it provides
isn't very elegant, compared to other functional languages. If you
want to write functional code, use a real functional language!

--
Evan Klitzke <ev**@yelp.co m>
Sep 18 '07 #2
The following defines the infinite list of primes as a generator [chap
6.5 of the library]

def sieve(l):
p = l.next()
yield p
for x in sieve(l):
if x % p != 0:
yield x

After that

from itertools import *
>>[p for i,p in izip(range(10), sieve(count(2)) )]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
>>>

I tried to write a shorter generator expression based sieve but cant
get it right.
Can someone help? Heres the non-working code

def si(l):
p = l.next()
yield p
(x for x in si(l) if x % p != 0)

There should be an yield or return somewhere but cant figure it out

On 9/18/07, Lorenzo Stella <lo******@gmail .comwrote:
Hi all,
I haven't experienced functional programming very much, but now I'm
trying to learn Haskell and I've learned that: 1) in functional
programming LISTS are fundmental; 2) any "cycle" in FP become
recursion.
I also know that Python got some useful tool such as map, filter,
reduce... so I told: "let's try some FP-style programming with
Python!". I took a little example of Haskell:

listprimes :: Integer -[Integer]
listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)]
where
sieve [] = []
sieve (p:xs) = p : sieve (filter (\x -mod x p 0) xs)

and I tried to "translate" it in Python:

def sieve(s):
if s == []:
return []
else:
return [s[0]] + sieve(filter((l ambda x: x % s[0] 0),
s[1:]))

def listprimes(n):
return sieve(range(2,n ))

These should be almost the same: listprimes actually lists prime
integers up to n-1. The result is: Haskell implementation works well,
maybe it's not the better way to do it, but it does what I wanted.
Python implementation gives me

RuntimeError: maximum recursion depth exceeded in cmp

My question is: how can we call a language "functional " if it's major
implementation has a limited stack? Or is my code wrong?

LS

--
http://mail.python.org/mailman/listinfo/python-list
Sep 18 '07 #3
Rustom Mody <ru*********@gm ail.comwrote:
Can someone help? Heres the non-working code

def si(l):
p = l.next()
yield p
(x for x in si(l) if x % p != 0)

There should be an yield or return somewhere but cant figure it out
Change last line to

for x in (x for x in si(l) if x % p != 0): yield x

if you wish.
Alex

Sep 18 '07 #4
On 9/18/07, Alex Martelli <al***@mac.comw rote:
Rustom Mody <ru*********@gm ail.comwrote:
Can someone help? Heres the non-working code

def si(l):
p = l.next()
yield p
(x for x in si(l) if x % p != 0)

There should be an yield or return somewhere but cant figure it out

Change last line to

for x in (x for x in si(l) if x % p != 0): yield x

Thanks but why does

(yield(x) for x in si(l) if x % p != 0)

not work? I would have expected generator expression to play better
with generators.

More generally, if one wants to 'splice in' a generator into the body
of a generator, is there no standard pythonic idiom?
Sep 18 '07 #5
On 18 Sep., 03:30, "Evan Klitzke" <e...@yelp.comw rote:
My question is: how can we call a language "functional " if it's major
implementation has a limited stack? Or is my code wrong?

Python does not optimize tail recursion.
Never mind. In the provided example the call to sieve() is not in tail
position anyway ;)

[...]
If you
want to write functional code, use a real functional language!
It's hard to disagree. As a Python programmer I'd rather care for
their particular programming idioms. For instance the Python - OCaml
bridge is aged and I'm not aware that one between Python and Haskell
even exists.
Sep 18 '07 #6
"Rustom Mody" <ru*********@gm ail.comwrote:
On 9/18/07, Alex Martelli <al***@mac.comw rote:
>Rustom Mody <ru*********@gm ail.comwrote:
Can someone help? Heres the non-working code

def si(l):
p = l.next()
yield p
(x for x in si(l) if x % p != 0)

There should be an yield or return somewhere but cant figure it out

Change last line to

for x in (x for x in si(l) if x % p != 0): yield x

Thanks but why does

(yield(x) for x in si(l) if x % p != 0)

not work? I would have expected generator expression to play better
with generators.
Why should it? It evaluates the expression which returns an object that
just happens to be a generator and then as with any other expression
that isn't assigned or returned it throws away the result.
More generally, if one wants to 'splice in' a generator into the body
of a generator, is there no standard pythonic idiom?
Yes there is, as Alex showed you the standard python idiom for a
generator to yield all elements of an iteratable (whether it is a
generator or any other iterable) is:

for somevar in iterable: yield somevar

There have been various proposals in the past such as 'yield from
iterable', but there doesn't seem any compelling case to introduce a new
confusing syntax: the existing syntax works, and adding a special syntax
wouldn't open the door to any performance benefits since the
implementation would have to be pretty much the same (at most you would
save a couple of local variable accesses).

Sep 18 '07 #7
Lorenzo Stella a écrit :
Hi all,
I haven't experienced functional programming very much, but now I'm
trying to learn Haskell and I've learned that: 1) in functional
programming LISTS are fundmental;
Not exactly. They are used quite a lot, yes, but that's also the case in
other paradigms. What's important in functional programming is *functions*.
2) any "cycle" in FP become
recursion.
FP idioms tends to use recursion instead of iteration, yes. But that's
only viable with implementations doing tail-recursion optimisation -
which is not the case with CPython (not that it couldn't FWIW - it's a
design choice, and one of the few I don't necessarily agree with).
I also know that Python got some useful tool such as map, filter,
reduce...
And all there itertools versions...
so I told: "let's try some FP-style programming with
Python!".
Most of the functional constructs that makes sens in Python are already
idiomatic. And some common functional stuff are better reimplemented the
pythonic way - as an example, while partial application is usually
implemented with closures, and *can* indeed be implemented that way in
Python, the class-based implementation is IMHO much better.
I took a little example of Haskell:

listprimes :: Integer -[Integer]
listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)]
where
sieve [] = []
sieve (p:xs) = p : sieve (filter (\x -mod x p 0) xs)

and I tried to "translate" it in Python:

def sieve(s):
if s == []:
return []
else:
return [s[0]] + sieve(filter((l ambda x: x % s[0] 0),
s[1:]))

def listprimes(n):
return sieve(range(2,n ))

These should be almost the same: listprimes actually lists prime
integers up to n-1. The result is: Haskell implementation works well,
maybe it's not the better way to do it, but it does what I wanted.
Python implementation gives me

RuntimeError: maximum recursion depth exceeded in cmp

My question is: how can we call a language "functional " if it's major
implementation has a limited stack? Or is my code wrong?
Strictly speaking, a language is functional if it has functions as first
class objects. Period. According to this definition, Python is a
functional language. Now that doesn't mean you should try to write
Haskell in Python... IOW, your code is not "wrong", but it's certainly
not the best way to implement such an algorithm in Python.

Sep 18 '07 #8
Lorenzo Stella <lo******@gmail .comwrites:
Hi all,
I haven't experienced functional programming very much, but now I'm
trying to learn Haskell and I've learned that: 1) in functional
programming LISTS are fundmental; 2) any "cycle" in FP become
recursion.
I also know that Python got some useful tool such as map, filter,
reduce... so I told: "let's try some FP-style programming with
Python!". I took a little example of Haskell:

listprimes :: Integer -[Integer]
listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)]
where
sieve [] = []
sieve (p:xs) = p : sieve (filter (\x -mod x p 0) xs)

and I tried to "translate" it in Python:

def sieve(s):
if s == []:
return []
else:
return [s[0]] + sieve(filter((l ambda x: x % s[0] 0),
s[1:]))

def listprimes(n):
return sieve(range(2,n ))

These should be almost the same: listprimes actually lists prime
integers up to n-1. The result is: Haskell implementation works well,
maybe it's not the better way to do it, but it does what I wanted.
Python implementation gives me

RuntimeError: maximum recursion depth exceeded in cmp

My question is: how can we call a language "functional " if it's major
implementation has a limited stack? Or is my code wrong?
It's no tthat it's "wrong", but doing recursion in python can be
problematic because there's no tail recursion optimisation and the
size of the stack is limited (so eventually you'll run out of stack if
you recurse deep enough).

One way to capture the spirit of that Haskell program in Python is to
use things from itertools; something like this (modified from
<http://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/117119>):
import itertools
def listprimes(n):

def sieve(nums):
seq = nums
while True:
prime = seq.next()
seq = itertools.ifilt er(prime.__rmod __, seq)
yield prime

if n == 0:
return sieve(itertools .count(2))
else:
return sieve(itertools .islice(itertoo ls.count(2), n-1))
>>list(listprim es(100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Sep 18 '07 #9
On 2007-09-18, Kay Schluehr <ka**********@g mx.netwrote:
On 18 Sep., 10:13, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
>Lorenzo Stella a écrit :
Hi all,
I haven't experienced functional programming very much, but now I'm
trying to learn Haskell and I've learned that: 1) in functional
programming LISTS are fundmental;

Not exactly. They are used quite a lot, yes, but that's also
the case in other paradigms. What's important in functional
programming is *functions*.

Functional lists are not quite the same. They are actually
recursive datastructes. In Python you would model them as
nested tuples:

t = (a, (b, (c, ...(d, None)))))
Tuples won't work for cyclic data, though.

--
Neil Cerutti
Sep 18 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.