kachayev / fn.py

Functional programming in Python: implementation of missing features to enjoy FP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fn.py: enjoy FP in Python

Despite the fact that Python is not pure-functional programming language, it's multi-paradigm PL and it gives you enough freedom to take credits from functional programming approach. There are theoretical and practical advantages to the functional style:

  • Formal provability
  • Modularity
  • Composability
  • Ease of debugging and testing

Fn.py library provides you with missing "batteries" to get maximum from functional approach even in mostly-imperative program.

More about functional approach from my Pycon UA 2012 talks: Functional Programming with Python.

Scala-style lambdas definition

More examples of using _ you can find in test cases declaration (attributes resolving, method calling, slicing).

Attention! If you work in interactive python shell, your should remember that _ means "latest output" and you'll get unpredictable results. In this case, you can do something like from fn import _ as X (and then write functions like X * 2).

If you are not sure, what your function is going to do, you can print it:

_ will fail with ArityError (TypeError subclass) on inaccurate number of passed arguments. This is one more restrictions to ensure that you did everything right:

Persistent data structures

Attention: Persistent data structures are under active development.

Persistent data structure is a data structure that always preserves the previous version of itself when it is modified (more formal information on Wikipedia). Each operation with such data structure yields a new updated structure instead of in-place modification (all previous versions are potentially available or GC-ed when possible).

Lets take a quick look:

If you think I'm totally crazy and it will work despairingly slow, just give it 5 minutes. Relax, take a deep breath and read about few techniques that make persistent data structures fast and efficient: structural sharing and path copying.

To see how it works in "pictures", you can check great slides from Zach Allaun's talk (StrangeLoop 2013): "Functional Vectors, Maps And Sets In Julia".

And, if you are brave enough, go and read:

  • Chris Okasaki, "Purely Functional Data Structures" (Amazon)
  • Fethi Rabhi and Guy Lapalme, "Algorithms: A Functional Programming Approach" (Amazon)

Available immutable data structures in fn.immutable module:

  • LinkedList: most "obvious" persistent data structure, used as building block for other list-based structures (stack, queue)
  • Stack: wraps linked list implementation with well-known pop/push API
  • Queue: uses two linked lists and lazy copy to provide O(1) enqueue and dequeue operations
  • Deque (in progress): "Confluently Persistent Deques via Data Structural Bootstrapping"
  • Deque based on FingerTree data structure (see more information below)
  • Vector: O(log32(n)) access to elements by index (which is near-O(1) for reasonable vector size), implementation is based on BitmappedTrie, almost drop-in replacement for built-in Python list
  • SkewHeap: self-adjusting heap implemented as a binary tree with specific branching model, uses heap merge as basic operation, more information - "Self-adjusting heaps"
  • PairingHeap: "The Pairing-Heap: A New Form of Self-Adjusting Heap"
  • Dict (in progress): persistent hash map implementation based on BitmappedTrie
  • FingerTree (in progress): "Finger Trees: A Simple General-purpose Data Structure"

Use appropriate doc strings to get more information about each data structure as well as sample code.

To get more clear vision of how persistent heaps work (SkewHeap and PairingHeap), you can look at slides from my talk "Union-based heaps" (with analyzed data structures definitions in Python and Haskell).

Note. Most functional languages use persistent data structures as basic building blocks, well-known examples are Clojure, Haskell and Scala. Clojure community puts much effort to popularize programming based on the idea of data immutability. There are few amazing talk given by Rich Hickey (creator of Clojure), you can check them to find answers on both questions "How?" and "Why?":

Streams and infinite sequences declaration

Lazy-evaluated Scala-style streams. Basic idea: evaluate each new element "on demand" and share calculated elements between all created iterators. Stream object supports << operator that means pushing new elements when it's necessary.

Simplest cases:

Lazy-evaluated stream is useful for infinite sequences, i.e. fibonacci sequence can be calculated as:

Trampolines decorator

fn.recur.tco is a workaround for dealing with TCO without heavy stack utilization. Let's start from simple example of recursive factorial calculation:

This variant works, but it's really ugly. Why? It will utilize memory too heavy cause of recursive storing all previous values to calculate final result. If you will execute this function with big n (more than sys.getrecursionlimit()) CPython will fail with

Which is good, cause it prevents you from terrible mistakes in your code.

How can we optimize this solution? Answer is simple, lets transform function to use tail call:

Why this variant is better? Cause you don't need to remember previous values to calculate final result. More about tail call optimization on Wikipedia. But... Python interpreter will execute this function the same way as previous one, so you won't win anything.

fn.recur.tco gives you mechanism to write "optimized a bit" tail call recursion (using "trampoline" approach):

@recur.tco is a decorator that execute your function in while loop and check output:

  • (False, result) means that we finished
  • (True, args, kwargs) means that we need to call function again with other arguments
  • (func, args, kwargs) to switch function to be executed inside while loop

The last variant is really useful, when you need to switch callable inside evaluation loop. Good example for such situation is recursive detection if given number is odd or even:

Attention: be careful with mutable/immutable data structures processing.

Itertools recipes

fn.uniform provides you with "unification" of lazy functionality for few functions to work the same way in Python 2+/3+:

  • map (returns itertools.imap in Python 2+)
  • filter (returns itertools.ifilter in Python 2+)
  • reduce (returns functools.reduce in Python 3+)
  • zip (returns itertools.izip in Python 2+)
  • range (returns xrange in Python 2+)
  • filterfalse (returns itertools.ifilterfalse in Python 2+)
  • zip_longest (returns itertools.izip_longest in Python 2+)
  • accumulate (backported to Python < 3.3)

fn.iters is high-level recipes to work with iterators. Most of them taken from Python docs and adopted to work both with Python 2+/3+. Such recipes as drop, takelast, droplast, splitat, splitby I have already submitted as docs patch which is review status just now.

  • take, drop
  • takelast, droplast
  • head (alias: first), tail (alias: rest)
  • second, ffirst
  • compact, reject
  • every, some
  • iterate
  • consume
  • nth
  • padnone, ncycles
  • repeatfunc
  • grouper, powerset, pairwise
  • roundrobin
  • partition, splitat, splitby
  • flatten
  • iter_except
  • first_true

More information about use cases you can find in docstrings for each function in source code and in test cases.

High-level operations with functions

fn.F is a useful function wrapper to provide easy-to-use partial application and functions composition.

It also give you move readable in many cases "pipe" notation to deal with functions composition:

You can find more examples for compositions usage in fn._ implementation source code.

fn.op.apply executes given function with given positional arguments in list (or any other iterable). fn.op.flip returns you function that will reverse arguments order before apply.

fn.op.foldl and fn.op.foldr are folding operators. Each accepts function with arity 2 and returns function that can be used to reduce iterable to scalar: from left-to-right and from right-to-left in case of foldl and foldr respectively.

Use case specific for right-side folding is:

Function currying

fn.func.curried is a decorator for building curried functions, for example:

Functional style for error-handling

fn.monad.Option represents optional values, each instance of Option can be either instance of Full or Empty. It provides you with simple way to write long computation sequences and get rid of many if/else blocks. See usage examples below.

Assume that you have Request class that gives you parameter value by its name. To get uppercase notation for non-empty striped value:

Hmm, looks ugly.. Update code with fn.monad.Option:

fn.monad.Option.or_call is good method for trying several variant to end computation. I.e. use have Request class with optional attributes type, mimetype, url. You need to evaluate "request type" using at least one attribute:

Installation

To install fn.py, simply:

$ pip install fn

Or, if you absolutely must:

$ easy_install fn

You can also build library from source

$ git clone https://github.com/kachayev/fn.py.git
$ cd fn.py
$ python setup.py install

Work in progress

"Roadmap":

  • fn.monad.Either to deal with error logging
  • C-accelerator for most modules

Ideas to think about:

  • Scala-style for-yield loop to simplify long map/filter blocks

Contribute

  1. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug.
  2. Fork the repository on Github to start making your changes to the master branch (or branch off of it).
  3. Write a test which shows that the bug was fixed or that the feature works as expected.

How to find me

  • Twitter: @kachayev
  • Email: kachayev <at> gmail.com

About

Functional programming in Python: implementation of missing features to enjoy FP

License:Other


Languages

Language:Python 100.0%