Live data from Hacker News

Functional programming in Python

docs.python.org

21–30 of 64 posts

Re: Functional programming in Python

#21
as has been pointed out, python isn't particularly great at doing hardcore functional programming due to lack of native persistant datastructures. however i've found it great for learning functional programming without having to get used to the syntax of real functional languages.

here are some different ways to implement functional sequence operations without native python syntax like `yield`:

https://github.com/dustingetz/sandbox/blob/master/etc/lazy.p... https://github.com/dustingetz/sandbox/blob/master/etc/map.py

and an unfinished, sloppy impl of monads in python with lots of minor errors:

http://www.dustingetz.com/2012/04/07/dustins-awesome-monad-t...

Re: Functional programming in Python

#22
post #12
post #11

Earlier quoted context omitted.

How about [item] + [some, list]?

That works but it's kind of a pain that the natural pythonic syntax: ['a'].extend(some-list) doesn't return a list.

that is not the natural pythonic syntax.

for concatenating lists, "+" is standard

Re: Functional programming in Python

#23
post #15

Earlier quoted context omitted.

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.

That's the problem. I can fake a functional paradigm within Python in some settings, but it falls apart at the seams.

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]

Re: Functional programming in Python

#24
post #11

Earlier quoted context omitted.

How about [item] + [some, list]?

Hmm, I forgot that '+' was overloaded for lists in Python - nevermind that last statement, then. The rest still holds, though - not all functions have a mutable and immutable counterpart (like sort) and map() returning lists makes them rather unwieldy. I think they fixed this in Python 3, though I'm not sure if it was backported to 2.7.

There's in-place .sort() and the functional sorted(), which has been there since at least 2.6. There's no in-place map, but it would be a one-line function (and you could use map as an in-place operator if you use a function for its side-effects). In the case of + there's the in-place counterpart += (same as extend for lists).

So I don't really get your concern, plus mutability is a property of data-structures, not of functions.

Re: Functional programming in Python

#25

as has been pointed out, python isn't particularly great at doing hardcore functional programming due to lack of native persistant datastructures. however i've found it great for learning functional programming without having to get used to the syntax of real functional languages. here are some different ways to implement functional sequence operations without native python syntax like `yield`: https://github.com/dus…

What do you mean with lack of persistent data-structures? There are immutable data-structures such as numbers, strings, tuples, and frozensets (unfortunately no frozen dicts) -- seems plenty to me. Or do you mean the technical meaning of persistent data-structures, as in one that gives access to all previous versions?

Re: Functional programming in Python

#26
post #5

What is really missing is a set of decent data structures.

What do you mean? What would you add on top of the built-ins and stdlib data structures?

There are situations where balanced search trees are appropriate. A general purpose priority queue (with delete and decrease-key operations); there's actually code for this in the _documentation_ of the heapq module; this seems really odd to me, why not just include it? It's also a shame that heapq is built on list instead of being a first-class data-structure, it feels bolted-on. Bitwise tries would be nice as well.

Re: Functional programming in Python

#27
post #20

One thing that's been key for me is namedtuple (in the collections module). It's immutable like a tuple, but the values can be accessed by name just as if they were object attributes built with the class keyword. It's great for creating generic functions (think Lisp and CLOS) instead of using Python's prototypical system. And since tuples can contain any objects and functions are objects, you can bind callables like…

if you want to append to fronts and backs of lists, you should use deque: http://docs.python.org/library/collections.html#collections....

pronounced "deck"

Re: Functional programming in Python

#28

as has been pointed out, python isn't particularly great at doing hardcore functional programming due to lack of native persistant datastructures. however i've found it great for learning functional programming without having to get used to the syntax of real functional languages. here are some different ways to implement functional sequence operations without native python syntax like `yield`: https://github.com/dus…

What do you mean with lack of persistent data-structures? There are immutable data-structures such as numbers, strings, tuples, and frozensets (unfortunately no frozen dicts) -- seems plenty to me. Or do you mean the technical meaning of persistent data-structures, as in one that gives access to all previous versions?

A good set of persistent data structures would give you all the generality, utility, and performance of Python data structures like lists and dicts and none of the mutability.

Re: Functional programming in Python

#29

One thing that's been key for me is namedtuple (in the collections module). It's immutable like a tuple, but the values can be accessed by name just as if they were object attributes built with the class keyword. It's great for creating generic functions (think Lisp and CLOS) instead of using Python's prototypical system. And since tuples can contain any objects and functions are objects, you can bind callables like…

    One thing I love about Lisp is that it's
    ridiculously easy to write (cons item some-list),
    or even (cons item1 (cons item2 some-list)).
Iterators can help (and in O(1)):

    >>> from itertools import chain
    >>> some_list = range(5)
    >>> item = 99
    >>> a = chain([item], some_list)
    >>> for x in a:
    ...     print x
    ...
    99
    0
    1
    2
    3
    4

Re: Functional programming in Python

#30

Earlier quoted context omitted.

Hmm, I forgot that '+' was overloaded for lists in Python - nevermind that last statement, then. The rest still holds, though - not all functions have a mutable and immutable counterpart (like sort) and map() returning lists makes them rather unwieldy. I think they fixed this in Python 3, though I'm not sure if it was backported to 2.7.

There's in-place .sort() and the functional sorted(), which has been there since at least 2.6. There's no in-place map, but it would be a one-line function (and you could use map as an in-place operator if you use a function for its side-effects). In the case of + there's the in-place counterpart += (same as extend for lists). So I don't really get your concern, plus mutability is a property of data-structures, not o…

> There's no in-place map

It's not a matter of in-place mapping, but if I remember correctly, map() returns a generator in Python3, which has the effect of simulating single-traversal and lazy evaluation like Haskell does.

> mutability is a property of data-structures, not of functions

True, but in a (purely) functional language, if all data structures are immutable and functions are simply mappings of input values to output values with no side-effects, that's inconsequential. We're talking about simulating a functional paradigm within a non-functional language with mutable data structures, so writing functions without side-effects would be more idiomatic - hence the problems with trying to write Python in a functional style.

Post reply on HN