471,338 Members | 1,308 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,338 software developers and data experts.

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((lambda 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 1598
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((lambda 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.setrecursionlimit, 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.com>
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((lambda 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*********@gmail.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.comwrote:
Rustom Mody <ru*********@gmail.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.comwrote:
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
smooth integration with code written in Haskell or OCaml than adopting
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*********@gmail.comwrote:
On 9/18/07, Alex Martelli <al***@mac.comwrote:
>Rustom Mody <ru*********@gmail.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((lambda 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((lambda 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.activestate.com/ASPN/Cookbook/Python/Recipe/117119>):
import itertools
def listprimes(n):

def sieve(nums):
seq = nums
while True:
prime = seq.next()
seq = itertools.ifilter(prime.__rmod__, seq)
yield prime

if n == 0:
return sieve(itertools.count(2))
else:
return sieve(itertools.islice(itertools.count(2), n-1))
>>list(listprimes(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**********@gmx.netwrote:
On 18 Sep., 10:13, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
>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
On 2007-09-18, Steve Holden <st***@holdenweb.comwrote:
Lorenzo Stella wrote:
[...]
>>
My question is: how can we call a language "functional" if
it's major implementation has a limited stack? Or is my code
wrong?

So, which environment do you habitually use that provides an
*unlimited* stack?
Perhaps Lorenzo Stella is referring to Python's lack of
tail-recursion optimization? There are languages that
guarantee unlimited tail-recursion with a limited stack.

That's a typical feature for a function language, right?
You just don't like the specific limit that Python imposes. So
increase it with sys.setrecursionlimit().
--
Grant Edwards grante Yow! I hope I bought the
at right relish ... zzzzzzzzz
visi.com ...
Sep 18 '07 #11
Grant Edwards a écrit :
On 2007-09-18, Steve Holden <st***@holdenweb.comwrote:
>>Lorenzo Stella wrote:
[...]
>>>My question is: how can we call a language "functional" if
it's major implementation has a limited stack? Or is my code
wrong?

So, which environment do you habitually use that provides an
*unlimited* stack?

Perhaps Lorenzo Stella is referring to Python's lack of
tail-recursion optimization? There are languages that
guarantee unlimited tail-recursion with a limited stack.

That's a typical feature for a function language, right?
And also for some implementations of some purely procedural languages IIRC.

Sep 18 '07 #12
On 18 Set, 18:51, Grant Edwards <gra...@visi.comwrote:
Perhaps Lorenzo Stella is referring to Python's lack of
tail-recursion optimization? There are languages that
guarantee unlimited tail-recursion with a limited stack.
That's it.

Rustom Mody: your implementation lacks exactly where mine does. Try
listing the first 2000 primes... That's what I meant: I cannot in
general (with Python) get such list just by defining *what* it is, I
have to express *how* to get it (describing an algorithm).

"What" or "How": that is the question.

Steve Holden wrote:
You just don't like the specific limit that Python imposes. So increase
it with sys.setrecursionlimit().
That is obviously not the answer to my question.

Sep 18 '07 #13
Rustom Mody asked:
[...] 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.
You have a statement, "yield(x)", where the construct requires
an expression.
--
--Bryan
Sep 19 '07 #14
Dear list members,
I am a newcomer in the world of Python. But I am attracted by Python's power in handling text! Now I apply it to handle Chinese but the Chinese character cann't be displayed on the screen. What displayed on the screen is the 16bits codes. I am so puzzled! I believe this is an easy question to most of python users and an important question to me. Thanks a lot to your help!


Sep 19 '07 #15
On Wed, 2007-09-19 at 13:57 +0800, Xing wrote:
Dear list members,
I am a newcomer in the world of Python. But I am attracted by
Python's power in handling text! Now I apply it to handle Chinese but
the Chinese character cann't be displayed on the screen. What
displayed on the screen is the 16bits codes. I am so puzzled! I
believe this is an easy question to most of python users and an
important question to me. Thanks a lot to your help!
You are not giving us any background information for troubleshooting
this. Your problem could be caused by a million different things, and
there is not point in us guessing. Please start by answering the
following questions:

1) What operating system are you using?
2) Can any programs on your computer display Chinese characters?
3) Where are you trying to display Chinese characters? Python command
line, in IDLE, in some GUI window?
4) Where are the Chinese characters you're trying to display coming
from? Are they hard-coded in your script, are they read from the
keyboard, from a file, from a database, from a web page?

--
Carsten Haese
http://informixdb.sourceforge.net
Sep 19 '07 #16

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

699 posts views Thread by mike420 | last post: by
176 posts views Thread by Thomas Reichelt | last post: by
21 posts views Thread by Anthony Baxter | last post: by
63 posts views Thread by Davor | last post: by
852 posts views Thread by Mark Tarver | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.