Friday, 24 January 2014

Enter the Rucksack

In these three variations we introduce an additional parcel of information that rides on the back of the central arguments and return values of  our function.  So the functional hamster has been fitted with a rucksack
and while the hamster keeps the important information in its cheeks the functions that we call are allowed to look inside the rucksack and can even take out what they find and put in something different.  The rodent
simile goes no further.  Anyway these three different examples show the pattern and of course patterns are what we are here to abstract out.  Enter the Rucksack.  Er, Monad I mean.

At this point I note that Erlang does have a format language for describing types of functions but I've not read up that far yet so I'll temporarily bodge it as follows.

So, instead of using functions F that take a plain value and return a plain result:

    F : x -> y

we start using enhanced functions that return an enhanced value:

    F' : x -> y'

In order to choreograph these functions we need a higher level function (generally called bind) that takes an enhanced value x' and an enhanced function F' and applies the one to the other taking care to maintain the additional information:

    bind : x',F' -> y'

In addition we need a little function called unit that goes from a naked value to an enhanced one without changing anything else:

    unit : x -> x'

Logic dictates that using unit to make a monadic value then binding to the function gives you the same result as applying the function to the original value: hope I got that right: anyway let there be a picture:

With this scheme in mind we can abstract out the maintenance of the additional information into a separate module.  So let's see.

No comments:

Post a Comment