005 - Pure, Functional, Financial Python Katas

Today, let's use Matplotlib only with lambdas.

If you have been following along, this will be simple.

And, if you haven't tried before, it is an easy entry point.

Re-implement the code you find here with lambdas only.

In [1]: %pylab  
In [2]: x = randn(10000)  
In [3]: hist(x, 100)  

~

Let's have a quick discussion of what we can and cannot do with lambdas.

Firstly it is clear that lambdas in Python are not functionally pure.

Pure functions always return the same values with the same arguments, e.g.

sum = lambda x, y: x + y

will always return the same outputs with the same inputs.

But for example,

rnd = lambda n: pylab.randn(n)

will not.

Every time we call rnd we will see a list of n different random numbers.

The same can be said for anything to do with time.

now = lambda: time.time()

Will return a unique value every time we call it.

We have secret inputs to both lambdas which we do not see. In the random case, it is a pseudo random number generator or seed. In the time case, we send the time function the current time from our machine's clock.

This implicitness can be a problem. Our code should read like mathematical equations in which everything is explicit.

However, we will see, that the use of lambdas everywhere instead of classes, variables etc. lowers the implicitness in our code.

While our code is impure we have limited the sources of impurities.

Also, while explicit functions are very robust, sometimes impurities help us - having impure time and random functions are in fact incredibly practical, versus the hoops we would need to jump through for pure versions.

~

Lambdas mean, inputs are for the most part explicit and our outputs are also.

Every lambda we code does one thing. We only have one output.

I.e. each lambda is an expression.

As opposed to a function or module which is a series of statements which do many things, lambda expressions output and do only one thing and can often be composed together and interchanged just like a mathematical formulae, which we will explore more in the coming days.