Functional Python Programming

(Wang) #1

The PyMonad Library


For Mac OS and Linux developers, the command pip install PyMonad or
easy_install-3.3 pymonad must be run using the sudo command. When running
a command such as sudo easy_install-3.3 pymonad, you'll be prompted for your
password to assure that you have the administrative permissions necessary to do the
installation. For Windows developers, the sudo command is not relevant, but you do
need to have administrative rights.


Once the pymonad package is installed, you can confirm it using the following
commands:





import pymonad
help(pymonad)





This will display the docstring module and confirm that things really are
properly installed.


Functional composition and currying


Some functional languages work by transforming a multiargument function syntax
into a collection of single argument functions. This process is called currying—it's
named after logician Haskell Curry, who developed the theory from earlier concepts.


Currying is a technique for transforming a multiargument function into higher order
single argument functions. In the simple case, we have a function fx(),yz→ ; given
two arguments x and y, this will return some resulting value, z. We can curry this
into two functions: fxc 1 ()→fyc 2 () and fyc 2 ()→z. Given the first argument value,
x, the function returns a new one-argument function, fxc 1 () returns a new one-
argument function, fyc 2 (). This second function can be given an argument, y, and
will return the resulting value, z.


We can evaluate a curried function in Python as follows: f_c(2)(3). We apply the
curried function to the first argument value of 2 , creating a new function. Then, we
apply that new function to the second argument value of 3.


This applies recursively to functions of any complexity. If we start with a function
g()abc,, →z, we curry this into a function gac 1 ()→→gbc 2 () gcc 3 ()→z. This is done
recursively. First, the gac 1 () function returns a new function with the b and c
arguments, gbc 2 (),cz→. Then we can curry the returned two-argument function to
create gbc 2 ()→gcc 3 ().


We can evaluate this curried function with g_c(1)(2)(3). When we apply gc 1 to an
argument of 1, we get a function; when we apply this returned function to 2, we get
another function. When we apply the final function to 3, we get the expected result.
Clearly, formal syntax is bulky, so we use some syntactic sugar to reduce g_c(1)(2)
(3) to something more palatable like g(1,2,3).

Free download pdf