Re:Functional programming in Python
by samdk on Friday May 11, 2012 @06:00PM
(#3961658)
Python lists are array-backed, Lisp lists are singly-linked lists. Appending to the front of an array list is O(n)--you don't want to do it. Appending to the back is constant time, but is an in-place operation and doesn't return anything, which is less than ideal for FP purposes.
[ Parent
| on HN ]
Re:Functional programming in Python
by chimeracoder on Friday May 11, 2012 @06:04PM
(#3961682)
That's the problem. I can fake a functional paradigm within Python in some settings, but it falls apart at the seams.
Re:Functional programming in Python
by groovy2shoes on Friday May 11, 2012 @06:19PM
(#3961740)
You can always use 2-tuples to get lists in the Lisp sense. You'd add an item to the head of a list by just pairing it:
lst = (2, (3, ()))
newlst = (1, lst)
Toss in some small helper functions and they become less unwieldy. You could pretty easily write an iterator for processing these lists: class List:
def __init__(self, lst):
self.cursor = lst
def __iter__(self):
return self
def next(self):
if self.cursor == ():
raise StopIteration
else:
head = self.cursor[0]
self.cursor = self.cursor[1]
return head
Then you can do stuff like: >>> for i in List(newlst):
... print i
...
1
2
3
>>> map(lambda x: x + 1, List(newlst))
[2, 3, 4]