473,841 Members | 1,837 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
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*********@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.

Similar topics

699
34362
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
49
2886
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville Vainio http://www.students.tut.fi/~vainio24
30
3531
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
176
8222
by: Thomas Reichelt | last post by:
Moin, short question: is there any language combining the syntax, flexibility and great programming experience of Python with static typing? Is there a project to add static typing to Python? Thank you, -- greetz tom
21
1631
by: Anthony Baxter | last post by:
On behalf of the Python development team and the Python community, I'm happy to announce the first alpha of Python 2.4. Python 2.4a1 is an alpha release. We'd greatly appreciate it if you could download it, kick the tires and let us know of any problems you find, but it is not suitable for production usage. http://www.python.org/2.4/ In this release we have a number of new modules, a number of existing
63
5204
by: Davor | last post by:
Is it possible to write purely procedural code in Python, or the OO constructs in both language and supporting libraries have got so embedded that it's impossible to avoid them? Also, is anyone aware of any scripting language that could be considered as "Python minus OO stuff"? (As you can see I'm completely new to Python and initially believed it's a nice&simple scripting language before seeing all this OO stuff that was added in over...
0
1279
by: Jack Diederich | last post by:
QOTW: "being able to cook an egg" - Guido Van Rossum in response to the question, "What do you think is the most important skill every programmer should posses?" "I am asking for your forgiveness" - an open letter to Guido by someone who took the "D" in "BDFL" too literally. Parsing a Grammar. Several solid tools are suggested. http://groups.google.com/group/comp.lang.python/browse_thread/thread/ea9736e13bd20fe2
852
29025
by: Mark Tarver | last post by:
How do you compare Python to Lisp? What specific advantages do you think that one has over the other? Note I'm not a Python person and I have no axes to grind here. This is just a question for my general education. Mark
0
9708
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10609
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10668
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10303
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5694
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4498
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4083
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3140
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.