Functional programming in Python

  • 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...

  • This is a useful reference but not really all that current. It dates back to 2006 - the functional constructs in Python now have evolved and changed over the years.

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

  • 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.

  • undefined

  • Its totally informative.I like your style dear.