Functional Python Programming

(Wang) #1
Chapter 14

There are two subclasses of the Maybe functor:



  • Nothing

  • Just(some simple value)


We use Nothing as a stand-in for the simple Python value of None. This is how we
represent missing data. We use Just(some simple value) to wrap all other Python
objects. These functors are function-like representations of constant values.


We can use a curried function with these Maybe objects to tolerate missing data
gracefully. Here's a short example:





x1= systolic_bp * Just(25) & Just(50) & Just(1) & Just(0)








x1.getValue()





116.09





x2= systolic_bp * Just(25) & Just(50) & Just(1) & Nothing








x2.getValue() is None





True


The * operator is functional composition: we're composing the systolic_bp()
function with an argument composite. The & operator builds a composite functor
that can be passed as an argument to a curried function of multiple arguments.


This shows us that we get an answer instead of a TypeError exception. This can
be very handy when working with large, complex datasets in which data could be
missing or invalid. It's much nicer than having to decorate all of our functions to
make them None aware.


This works nicely for curried functions. We can't operate on the Maybe functors in
uncurried Python code as functors have very few methods.


We must use the getValue() method to extract the simple
Python value for uncurried Python code.

Using the lazy List() functor


The List() functor can be confusing at first. It's extremely lazy, unlike Python's
built-in list type. When we evaluate the built-in list(range(10)) method, the
list() function will evaluate the range() object to create a list with 10 items.
The PyMonad List() functor, however, is too lazy to even do this evaluation.

Free download pdf