Live data from Hacker News

Functional programming in Python

docs.python.org

1–10 of 64 posts

Re: Functional programming in Python

#7
post #5

Earlier quoted context omitted.

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

I believe he is talking about persistent data structures.

Link for convenience: http://en.wikipedia.org/wiki/Persistent_data_structure

“… a persistent data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (visibly) update the structure in-place, but instead always yield a new updated structure.”

Re: Functional programming in Python

#9
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 lambdas to those names, which allows you to have 'methods' if you want as well.

That said, the standard library leaves something to be desired for the functional style. It makes sense for object-oriented programming to have non-mutating functions return the result and mutating functions return None (think sorted vs. sort), but this can get rather irritating when you're trying to write in a purely functional paradigm.

Also, am I forgetting my Python, or does it not have a great solution for appending to the front of a list? 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)). Doing the same thing in Python is irritating, because insert() doesn't return the result list.

...or maybe that's what I deserve for trying to write Lisp-like code in Python, anyway....!

EDIT: As noted in the comments, the '+' operator will suffice here. Though since lists are really arrays and not linked lists, this functional way of thinking will result in horribly inefficient CPython code.

Re: Functional programming in Python

#10

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

I doubt you'll see that - at least in CPython. Guido's been very clear about how he feels about implementing functional paradigms in Python, so it will probably never support functional programming in the standard implementation - just a bit in syntax/interface.
Post reply on HN