Latest revision as of 06:26, 18 September 2008

is a nice little module which shows off some of the features of the various monads around.
The task is to write a function

compose ::[a -> a]->(a -> a)

, which should take a list of functions and chain them together: a value would be fed into the first, which then produces a new value, which is fed into the second, and so on. I.e.

compose [(*2),(+1)]3=7

.

This page illustrates the solution in different monads. Most are a bit of a joke; you'd probably only ever use the first solution presented, but nevertheless the nice features of the various monads are demonstrated.

is a simple function that just returns the current environment.
Our tactic in words here is to create a computation (the result of the

compose'

call) which modifies the environment for another computation which further modifies the environment for another computation which modifies the environment yet further... until finally we hit the end of our list and we just return the environment, which has had all the functions in our list applied to it.

Once this composition has been built up, we run it, starting off with an environment of the starting value.

in this way. This example was really just an experimentation to see if

Writer

could be twisted in this way!
Our tactic here is really rather similar to that of the

Reader

example. We build up a computation which is the result of modifying the environment (or, actually, as we're working in

Writer

, we modify the output).

censor

, to quote All About Monad, "...takes a function and a

Writer

and produces a new

Writer

whose output is the same but whose log entry has been modified by the function.". So, we compose each function in turn onto the "log output" (which is actually a chain of composed functions).

Once this computation has been built up, we extract this long composition chain, and apply it to our starting value.

Also interesting to note is that this method is really equivalent to the "Sane method" described above. We just iterate along the list, accumulating a composition chain. The only difference here is that we're using some of

loop above, but uses a pair as the passed parameter. It walks down the list, accumulating the composition chain. Instead of building a composition chain, it is possible to act on the value directly, a bit like with the