<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>Where misquotes, misinformation, and misspellings occur daily.</description><title>Disfunctional</title><generator>Tumblr (3.0; @drboolean)</generator><link>http://drboolean.tumblr.com/</link><item><title>Monads as I understand them</title><description>&lt;p&gt;To be honest, it took me a ton of tutorials - a ton - before I could look you in the eye and say I understand what the hell a monad is.&lt;br/&gt;&lt;br/&gt;

I believe the reason for this is not because they are hard, but because all those tutorials didn&amp;#8217;t build upon my basic understanding of functors. Functors are much easier to understand. If you need a refresher read this:  &lt;a href="http://drboolean.tumblr.com/post/25413244757/functor-i-hardly-knew-her"&gt;http://drboolean.tumblr.com/post/25413244757/functor-i-hardly-knew-her&lt;/a&gt;
&lt;br/&gt;&lt;br/&gt;
Or have a play with them yourself:  &lt;a href="https://github.com/loop-recur/typeclasses"&gt;https://github.com/loop-recur/typeclasses&lt;/a&gt;
&lt;br/&gt;&lt;br/&gt;

In this post, I hope to take the quickest path to explaining monads without taking all the detours due to their vast usage and abstract nature.

&lt;h2&gt;Why we have monads in the first place&lt;/h2&gt;&lt;br/&gt;

What follows is our naive program. In a perfect world we could write this:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ getUser :: Number -&amp;gt; User
var getUser = db.find('users');

//+ parseUrl :: String -&amp;gt; Number
var parseUrl = compose(pluck(1), match(/users\/(\d+)/));

//+ urlToUser :: String -&amp;gt; User
var urlToUser = compose(getUser, parseUrl);
&lt;/code&gt;&lt;/pre&gt;

Our entry point is &lt;strong&gt;urlToUser&lt;/strong&gt;. It will take a url string to parse and extract the id from then it will give that to &lt;strong&gt;getUser&lt;/strong&gt; to find our user.&lt;br/&gt;&lt;br/&gt;

I said this representation is naive because there are a few places we can fail. Let&amp;#8217;s start with it failing on the &lt;strong&gt;parseUrl&lt;/strong&gt; function. This function may or may not find a match from our &lt;strong&gt;match(/users\/(\d+)/)&lt;/strong&gt; and it will blow up with a &lt;em&gt;TypeError: Cannot read property &amp;#8216;1&amp;#8217; of null&lt;/em&gt; if it can&amp;#8217;t!&lt;br/&gt;&lt;br/&gt;

This will never do. Since every monad is a functor and functors are easier to understand, lets start there. Functors to the rescue!

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ getUser :: Number -&amp;gt; User
var getUser = db.find('users');

//+ parseUrl :: String -&amp;gt; Maybe(Number)
var parseUrl = compose(fmap(pluck(1)), Maybe, match(/users\/(\d+)/));

//+ urlToUser :: String -&amp;gt; Maybe(User)
var urlToUser = compose(fmap(getUser), parseUrl);
&lt;/code&gt;&lt;/pre&gt;

What we had to do is place our match result into a &lt;strong&gt;Maybe&lt;/strong&gt;. This forces the rest of our code to deal with the fact that we may or may not have a match in &lt;strong&gt;pluck(1)&lt;/strong&gt; and &lt;strong&gt;getUser&lt;/strong&gt;.&lt;br/&gt;&lt;br/&gt;

The real thing to think about here is what we&amp;#8217;ve done typewise. In &lt;strong&gt;urlToUser&lt;/strong&gt;, we&amp;#8217;ve composed &lt;strong&gt;parseUrl :: String -&amp;gt; Maybe(Number)&lt;/strong&gt; with &lt;strong&gt; getUser ::  Number -&amp;gt; User&lt;/strong&gt;. Those types shouldn&amp;#8217;t line up since &lt;strong&gt;getUser&lt;/strong&gt; takes a &lt;strong&gt;Number&lt;/strong&gt; not a &lt;strong&gt;Maybe(Number)&lt;/strong&gt;. Through the magic of &lt;strong&gt;fmap&lt;/strong&gt; which opens up our &lt;strong&gt;Maybe&lt;/strong&gt; and runs the function on it&amp;#8217;s innards, we pass our &lt;strong&gt;Number&lt;/strong&gt; to &lt;strong&gt;getUser&lt;/strong&gt; instead of the &lt;strong&gt;Maybe(Number)&lt;/strong&gt; and all is well.&lt;br/&gt;&lt;br/&gt;

You could say we composed these types:&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;a -&amp;gt; F(b)&lt;/strong&gt; (parseUrl)&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;b -&amp;gt; c&lt;/strong&gt; (getUser)&lt;br/&gt;&lt;br/&gt;
And ended up with:&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;a -&amp;gt; F(c)&lt;/strong&gt; (urlToUser)&lt;br/&gt;&lt;br/&gt;

Where &lt;strong&gt;F&lt;/strong&gt; is the functor (in this case Maybe). K, great. We understand functors and all that, but what about monads?!&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Getting more robust&lt;/h2&gt;&lt;br/&gt;

Well, we caught the first failure case, but there&amp;#8217;s another one. What if &lt;strong&gt;getUser&lt;/strong&gt; doesn&amp;#8217;t actually find a user?! Total code anarchy. Let&amp;#8217;s catch this case now*:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ getUser :: Number -&amp;gt; Maybe(User)
var getUser = compose(Maybe, db.find('users'));

//+ parseUrl :: String -&amp;gt; Maybe(Number)
var parseUrl = compose(fmap(pluck(1)), Maybe, match(/users\/(\d+)/));

//+ urlToUser :: String -&amp;gt; Maybe(Maybe(User))
var urlToUser = compose(fmap(getUser), parseUrl);
&lt;/code&gt;&lt;/pre&gt;

Darn it. We wanted &lt;strong&gt;urlToUser&lt;/strong&gt; to return a &lt;strong&gt;Maybe(User)&lt;/strong&gt;, but we returned a &lt;strong&gt;Maybe(Maybe(User))&lt;/strong&gt;. Since &lt;strong&gt;fmap&lt;/strong&gt; re-wraps up the type for us and &lt;strong&gt;getUser&lt;/strong&gt; returns a &lt;strong&gt;Maybe&lt;/strong&gt; too, we get a nested Maybe that we need to flatten. &lt;em&gt;This is precisely the time to use a monad.&lt;/em&gt; Luckily, &lt;strong&gt;Maybe&lt;/strong&gt; is a monad in addition to being a functor.&lt;br/&gt;&lt;br/&gt;

There is this great function called &lt;strong&gt;mjoin&lt;/strong&gt; that we need to use. It&amp;#8217;s specific to each monad instance. For &lt;strong&gt;Maybe&lt;/strong&gt; it works like this:
&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
mjoin(Maybe(Maybe("hello monad"))) // Maybe("hello monad")

mjoin(Maybe(Maybe(null))) // Maybe(null)
&lt;/code&gt;&lt;/pre&gt;

&lt;pre class="prettyprint"&gt;	
&lt;code class="language-javascript"&gt;
//+ urlToUser :: String -&amp;gt; Maybe(User)
var urlToUser = compose(mjoin, fmap(getUser), parseUrl);
&lt;/code&gt;&lt;/pre&gt;

Boom! We just flattened the instance and we&amp;#8217;re good to go. Congrats, you just used the &lt;strong&gt;Maybe&lt;/strong&gt; monad! It was really that easy.&lt;br/&gt;&lt;br/&gt;

So back to types. We needed to compose &lt;strong&gt;parseUrl :: String -&amp;gt; Maybe(Number)&lt;/strong&gt; with &lt;strong&gt;getUser ::  Number -&amp;gt; Maybe(User)&lt;/strong&gt;. This is exactly the pattern we want to recognize as monadic composition or in other words, composing two functions that take normal values, but return monadic values.

Here&amp;#8217;s the abstract pattern:&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;a -&amp;gt; M(b)&lt;/strong&gt; (parseUrl)&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;b -&amp;gt; M(c)&lt;/strong&gt; (getUser)&lt;br/&gt;&lt;br/&gt;
And ended up with:&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;a -&amp;gt; M(c)&lt;/strong&gt; (urlToUser)&lt;br/&gt;&lt;br/&gt;

We used &lt;strong&gt;M&lt;/strong&gt; for monad in the types above instead of &lt;strong&gt;F&lt;/strong&gt; for functor since we&amp;#8217;ll need the ability to call &lt;strong&gt;mjoin&lt;/strong&gt; on it afterwards to flatten it up.

&lt;h2&gt;So monads are functors that flatten?&lt;/h2&gt;&lt;br/&gt;

Well, yes…but it goes further than that. Just stay with me here as we go through the final trick.&lt;br/&gt;&lt;br/&gt;

If we wanted to compose lots of monadic functions it would get real awkward real fast since &lt;strong&gt;mjoin&lt;/strong&gt; only flattens our values once and we&amp;#8217;d see a lot of &lt;strong&gt;compose(mjoin, fmap)&lt;/strong&gt; everywhere.&lt;br/&gt;&lt;br/&gt;

The real power of monads comes from our &lt;strong&gt;mbind&lt;/strong&gt; function. This function is defined as just the combination of &lt;strong&gt;fmap&lt;/strong&gt; and &lt;strong&gt;mjoin&lt;/strong&gt; as you would expect, but with a few quirks:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ mbind :: M(a) -&amp;gt; (a -&amp;gt; M(b)) -&amp;gt; M(b)
var mbind = function(mv, f) {
  return compose(mjoin, fmap(f))(mv);
}
&lt;/code&gt;&lt;/pre&gt;

The first thing to notice is we&amp;#8217;ve flipped the arguments to around (value, then function). This is because it&amp;#8217;s setup for chaining/nesting. Check it out:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ addMaybes :: Maybe(Number) -&amp;gt; Maybe(Number) -&amp;gt; Maybe(Number)
var addMaybes = function(ma, mb) {
  return mbind(ma, function(a) {
    return mbind(mb, function(b) {
      return Maybe(a + b);
    });
  });
}

addMaybes(Maybe(3), Maybe(4)) // Maybe(7)
addMaybes(Maybe(null), Maybe(4)) // Maybe(null)
&lt;/code&gt;&lt;/pre&gt;

This is just like our node.js &amp;#8220;pyramid of doom&amp;#8221; nested callback style. The reason that&amp;#8217;s so powerful is that:&lt;br/&gt;&lt;br/&gt;&lt;b&gt;1. We can depend on the values from the previous expressions&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;
We get access to &lt;strong&gt;a&lt;/strong&gt; and &lt;strong&gt;b&lt;/strong&gt; to use together. We can keep &lt;strong&gt;mbind&lt;/strong&gt;-ing deeper and deeper and pretend as though all the values have succeeded and are there.&lt;br/&gt;&lt;br/&gt;&lt;b&gt;2. We can prevent the nested functions from running all together&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;
If anything isn&amp;#8217;t there, we&amp;#8217;ll never reach the following function since &lt;strong&gt;Maybe&lt;/strong&gt; won&amp;#8217;t even run it.  And since the rest of the functions are nested the whole process gets shut down right then and there.&lt;br/&gt;&lt;br/&gt;

Both of these features are unique to monads and are what make a them more powerful than functors/applicatives. So use that when you&amp;#8217;re making a decision on whether or not you need to use a monad or not.  Usually it&amp;#8217;s better to not use them if you can get away with something simpler.&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Lastly, …for now&lt;/h2&gt;&lt;br/&gt;

There&amp;#8217;s a whole lot of monad stuff to learn. I could talk about pointed functors and keeping it type generic by using &lt;strong&gt;mresult&lt;/strong&gt;, I could talk about &lt;strong&gt;mcompose&lt;/strong&gt; or &lt;strong&gt;ap&lt;/strong&gt; or the monoid instance &lt;strong&gt;MonadPlus&lt;/strong&gt;, but I wanted to point out one last little feature for now. &lt;strong&gt;liftM&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;

liftM keeps us point free and simple. It works just like &lt;strong&gt;fmap&lt;/strong&gt;, but for monads:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ addMaybes :: M(Number) -&amp;gt; M(Number) -&amp;gt; M(Number)
var addMaybes = liftM("+");

liftM(function(x){ return x + 1; }, Maybe(4)) // Maybe(5)

liftM(function(x, y){ return x + y; }, Maybe(4), Maybe(5)) // Maybe(9)

liftM(function(x, y){ return x + y; }, Maybe(4), Maybe(null)) // Maybe(null)
&lt;/code&gt;&lt;/pre&gt;

When &lt;strong&gt;liftM&lt;/strong&gt; is given multiple arguments, it nests each value as if we were writing our &lt;strong&gt;mbind&lt;/strong&gt; manually.&lt;br/&gt;&lt;br/&gt;

So there you have it!&lt;br/&gt;&lt;br/&gt;


*Something to mention is that &lt;strong&gt;db.find&lt;/strong&gt; should probably return a &lt;strong&gt;Maybe(a)&lt;/strong&gt; by design. This would force us to deal with the nulls and make our program more robust from the start. If you contrast that to just returning null like we did in the previous example, you can see that these types really do help you write a more correct program.&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/37087696863</link><guid>http://drboolean.tumblr.com/post/37087696863</guid><pubDate>Sun, 02 Dec 2012 19:27:00 -0800</pubDate></item><item><title>Tail call optimization on it's way... Who gives a frak?!</title><description>&lt;p&gt;I&amp;#8217;m going to talk about capturing different recursive patterns in higher order functions and how we are better off with them over explicit recursion anyways.  But first, let&amp;#8217;s quickly go over what recursion is in javascript and why we might care about it.
&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Recursion in javascript&lt;/h3&gt;

What is recursion?  Well, it&amp;#8217;s just calling a function from within itself.  It is usually used as a replacement for loops in functional languages.
&lt;br/&gt;&lt;br/&gt;

Let&amp;#8217;s define a recursive version of Array#reverse.  We need a couple of helper functions: head and tail.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
head = function(xs) {
  return xs[0];
};

tail = function(xs) {
  return xs.slice(1, xs.length);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;strong&gt;head&lt;/strong&gt; will grab the first item in an array and &lt;strong&gt;tail&lt;/strong&gt; will return everything but the first item.  Now then, reverse!

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
reverse = function(xs) {
  if(xs.length == 0) return xs;
  return reverse(tail(xs)).concat(head(xs));
}

reverse([1,2,3,4]) // [4,3,2,1]
&lt;/code&gt;&lt;/pre&gt;

First, we create a &lt;strong&gt;base case&lt;/strong&gt; that returns the empty array if the length is 0.  This prevents us from looping forever.  Then, we just &lt;strong&gt;concat&lt;/strong&gt; the first item with the result of calling this function recursively on the tail, essentially sticking it on the end of the new array we&amp;#8217;re building.

&lt;br/&gt;&lt;br/&gt;

When I first was acquainted with recursion, I kept trying to visualize the stack and each step in the process.  Now, I find it much easier to just mentally replace the recursive call with what would be the result.  In this case, that would be &lt;strong&gt;return [4,3,2].concat(1);&lt;/strong&gt;

&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Okay, on with the show&lt;/h3&gt;

&lt;strong&gt;reverse&lt;/strong&gt; doesn&amp;#8217;t have to be defined recursively.  We can use a good old fashion loop.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
reverse = function(xs) {
  var result = [];
  
  for(x in xs) {
    result = [xs[x]].concat(result);
  }
  return result;
}
&lt;/code&gt;&lt;/pre&gt;

There are some benefits of recursion.  It&amp;#8217;s elegant, it reads well, it&amp;#8217;s not creating messy variables to keep state or reassigning/destroying them.  But in javascript, it is not very practical.  For one, the syntax is a bit clunky.  If you contrast this with an erlang or haskell example, it highlights how unnatural recursion is in javascript.  Here&amp;#8217;s haskell:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-haskell"&gt;
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
&lt;/code&gt;&lt;/pre&gt;

The (x:xs) part uses built in pattern matching to extract the head from the tail of the array.  Also we can define the function twice - once for the base case.
&lt;br/&gt;&lt;br/&gt;
A second reason recursion isn&amp;#8217;t very practical in javascript is the compiler is not optimized to keep track of all the recursive calls.  They say tail call optimization is coming, which is a compiler trick to release memory during each iteration, but I say don&amp;#8217;t worry, we can do better than both of these&amp;#8230;

&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;A better way&lt;/h3&gt;

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
reverse = reduce(function(acc, x){ return [x].concat(acc); }, []);
&lt;/code&gt;&lt;/pre&gt;

Check that out!  We don&amp;#8217;t have to specify any iteration at all.  We can just leave it to the &lt;strong&gt;reduce&lt;/strong&gt; function to figure that out.  I&amp;#8217;ve used &lt;a href="http://drboolean.tumblr.com/post/22931848110/partial-application"&gt;partial application&lt;/a&gt; here and only gave &lt;strong&gt;reduce&lt;/strong&gt; two of it&amp;#8217;s &lt;a href="http://osteele.com/sources/javascript/functional/"&gt;three&lt;/a&gt; arguments.
&lt;br/&gt;&lt;br/&gt;

What&amp;#8217;s more, since I&amp;#8217;m familiar with the function, I know just by reading the word &lt;strong&gt;reduce&lt;/strong&gt; that we&amp;#8217;re capturing a specific recursion pattern where the base case is an empty list and for each iteration we apply a function to an accumulator and the element from the list.  Here it is explicitly:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
reduce = function(f, acc, xs) {
  if(xs.length == 0) return acc;
  return reduce(f, f(acc, head(xs)), tail(xs));
}
&lt;/code&gt;&lt;/pre&gt;

Now, reduce isn&amp;#8217;t actually implemented using this recursion pattern above for performance reasons, but that makes no difference to us.  We captured the pattern in a named abstraction (reduce) and now we&amp;#8217;re unshackled from the chains of iteration&amp;#8230;or something like that.

&lt;br/&gt;&lt;br/&gt;

The pattern we just witnessed was a &lt;strong&gt;catamorphism&lt;/strong&gt; - your basic &lt;strong&gt;fold&lt;/strong&gt;.*  In fact, most languages call reduce &lt;strong&gt;foldl&lt;/strong&gt; for fold left.

&lt;br/&gt;&lt;br/&gt;

Our beloved &lt;strong&gt;map&lt;/strong&gt; is just a specific implementation of this recursion pattern.  So is &lt;strong&gt;filter&lt;/strong&gt;.  That means we can implement each of these methods in terms of reduce.

&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;But wait, there&amp;#8217;s more&lt;/h3&gt;

There isn&amp;#8217;t just one type of recursion pattern out there.  There are a number of them and each have their own qualities.  For instance, if, in addition to the accumulator and current element, you want access to the rest of the array during each iteration use a &lt;strong&gt;paramorphism&lt;/strong&gt;.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
paraReduce = function(f, acc, xs) {
  if(xs.length == 0) return acc;
  return paraReduce(f, f(acc, head(xs), xs), tail(xs));
}
&lt;/code&gt;&lt;/pre&gt;

This is just like the catamorphism, except that we pass the extra &lt;strong&gt;xs&lt;/strong&gt; into the supplied function.
&lt;br/&gt;&lt;br/&gt;

On top of instant recognition of the named pattern, DRY code, and easy swapping of recursion strategies, we&amp;#8217;ve opened the door to different implementations of our underlying loop.  That means we can optimize under the hood.

&lt;br/&gt;&lt;br/&gt;

There&amp;#8217;s a law (via functors) that states the following:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
compose(map(f), map(g)) == map(compose(f, g))
&lt;/code&gt;&lt;/pre&gt;

So instead of looping through the whole array and running &lt;strong&gt;g&lt;/strong&gt;, then doing the whole thing again and running &lt;strong&gt;f&lt;/strong&gt;, we can just make 1 loop and run &lt;strong&gt;compose(f, g)&lt;/strong&gt; for the same result.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
// not fused
compose(map("*2"), map("+1"))

// fused
map(compose("*2", "+1"))
}
&lt;/code&gt;&lt;/pre&gt;

We can also use our abstractions to run in parallel or add any other optimizations you can imagine.  If we had two explicit loops going on there, it&amp;#8217;d be very difficult to make this kind of change.  The point is when you program declaratively you leave room for different implementation.

&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;A vulgar display of explicit iteration&lt;/h3&gt;

So in conclusion, I say frak the tail-call optimization!  We&amp;#8217;re reaping the all benefits of abstraction, labeling our patterns for easy understanding, writing smaller, more concise code&amp;#8230;why did we want all this messy recursion back in our applications again anyways?

&lt;br/&gt;&lt;br/&gt;&lt;small&gt;
*Hopefully, I&amp;#8217;ll do a post on &lt;strong&gt;anamorphisms&lt;/strong&gt; (or unfolds) soon.  Until then, check out &lt;a href="http://www.cs.ox.ac.uk/jeremy.gibbons/publications/origami.pdf"&gt;this paper&lt;/a&gt;
&lt;/small&gt;&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/32646046753</link><guid>http://drboolean.tumblr.com/post/32646046753</guid><pubDate>Sun, 30 Sep 2012 19:40:00 -0700</pubDate></item><item><title>I do declare</title><description>&lt;p&gt;&lt;h3&gt;Brian vs Abstraction Round 1&lt;/h3&gt;
Martin Fowler once said something to the effect that programming, at it&amp;#8217;s finest, should be nothing more than the configuration of abstractions.  This made a little bit of my brain leak out my ear the first time I read it.  It was a statement that made me question everything I&amp;#8217;d written up until that point.  It was brilliant!  I was going to make abstractions, then configure them in every application from then on out.  No more inline, single use nonsense.

&lt;br/&gt;&lt;br/&gt;
Over the next week at work, after spending half of each day abstracting things, I realized that no one really has the time to pull this off.  It&amp;#8217;d have to be a group effort:  Everyone making super configurable abstractions and explaining to each other how to use them via doc or tutorial or whatever.  But things keep changing, the ground moves below our feet, technology, languages, etc.  It was useless to try to abstract everything.
&lt;br/&gt;&lt;br/&gt;

But back then, I hadn&amp;#8217;t seen the whole story.  I was trapped in OO land where nouns and specific implementations dominated.  Where functions were tucked away for use with only their owning objects.  Where the specific application&amp;#8217;s data was tangled up with the very functions we were trying to make data agnostic.  Where generic behavior was forced into the back alleys of abstract interfaces.  Now, after functional programming changed my perspective, I could revisit the dream.
&lt;br/&gt;&lt;br/&gt;

In functional programming, we build bigger systems from the same old reusable set of functions.  We look at shared behavior and functionality more like traits and say a thing is a functor or a monoid, not an address or a user.  We create contexts so we can use those same functions in different ways on different things, but in the end, it&amp;#8217;s the same set of functions.  The dream may be possible after all!
&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Brian vs Abstraction Round 2&lt;/h3&gt;

Anyways, this is a post on declarative programming.  Declarative programming gets to the heart of what Fowler was saying as we will see.
&lt;br/&gt;&lt;br/&gt;

Declarative programming is where you say what should happen in your application and walk away - you don&amp;#8217;t actually &lt;em&gt;do&lt;/em&gt; anything.  You then allow the underlying mechanism, be it a framework or language or some other (higher order) code, to accomplish the tasks however it sees fit.  Imperative programming, on the other hand, is where you take the reigns and tell the computer how to do each  step right then and there in the midst of your business logic.
&lt;br/&gt;&lt;br/&gt;

Maybe that&amp;#8217;s not the most unbiased definition, but let&amp;#8217;s keep digging and you&amp;#8217;ll see what I mean.  The primary example I see everywhere is SQL.  You express a query as a single expression and let the computer do it’s job. This is much different than say, a typical c program where you specify each individual step down to memory allocation right there in your function. 
&lt;br/&gt;&lt;br/&gt;

Another example is relationships in rails.  ActiveRecord users will recognize the example of adorning models with &lt;strong&gt;has_many&lt;/strong&gt; and &lt;strong&gt;belongs_to&lt;/strong&gt;.  You declare the relationship and leave it to the superclass to make it happen.
&lt;br/&gt;&lt;br/&gt;

There are many benefits to this style of programming.  Most of them stem from the fact that you&amp;#8217;re kind of forced to abstract all the functionality in order to write a declarative line.  But the style itself leads you to an agile application that reads like a book if you do it right.
&lt;br/&gt;&lt;br/&gt;

Here&amp;#8217;s a bite size example:
&lt;br/&gt;&lt;br/&gt;
Imperative

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var chargeCard = function(credit_card) {
  if(chargeCard(credit_card)) {
    sendReceipt(credit_card);
    updatePaidStatus(credit_card);
  } else {
    cancelAccount(credit_card.user);
  }
  return credit_card;
}
&lt;/code&gt;&lt;/pre&gt;


Declarative
&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ chargeCard :: CreditCard -&amp;gt; CreditCard
var chargeCard = ifelse(chargeCard, compose(updatePaidStatus, sendReceipt), compose(cancelAccount, '.user'));
&lt;/code&gt;&lt;/pre&gt;

You might initially think they are about the same, except the declarative one is much worse on the eyes. But wait, there are some hidden benefits beside brevity.  For one, the declarative version has the ability to alter the strategy of how these functions work together.  Just by changing &lt;strong&gt;compose&lt;/strong&gt;, we might parellelize some things or we could alter &lt;strong&gt;ifelse&lt;/strong&gt; to do some tracing in between each step.
&lt;br/&gt;&lt;br/&gt;

Another benefit is the ability to compose small pieces together to build up a bigger, more readable function.  One expression of self contained bits can be manipulated much easier than several lines of separate steps with loose variables and such lying around.  You simply copy and paste little chunks of code around and wrap them in &lt;strong&gt;compose&lt;/strong&gt;.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ cancelUsersAccount :: CreditCard -&amp;gt; void
var cancelUsersAccount = compose(cancelAccount, '.user');

//+ finishPayment :: CreditCard -&amp;gt; CreditCard
var finishPayment = compose(updatePaidStatus, sendReceipt);

//+ chargeCard :: CreditCard -&amp;gt; CreditCard
var chargeCard = ifelse(chargeCard, finishPayment, cancelUsersAccount);
&lt;/code&gt;&lt;/pre&gt;

And and there it is.  If you look at chargeCard, there&amp;#8217;s that declarative &amp;#8220;what&amp;#8221; I was looking for written out in plain english.
&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Showing off&lt;/h3&gt;
Let&amp;#8217;s do a few optimizations to show off a bit.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
//+ cancelUsersAccount :: CreditCard -&amp;gt; void
var cancelUsersAccount = memoize(compose(cancelAccount, '.user'));

//+ finishPayment :: CreditCard -&amp;gt; CreditCard
var finishPayment = compose_p(updatePaidStatus, sendReceipt);
&lt;/code&gt;&lt;/pre&gt;

We&amp;#8217;ve just &lt;strong&gt;memoized&lt;/strong&gt;(cached) the &lt;strong&gt;cancelUsersAccount&lt;/strong&gt; function so it doesn&amp;#8217;t actually run that function twice with the same user - it will just return the result the second time.  Usually, that helps with long calculations, but in this case it just prevents us from accidentally running a db call again for no reason since it&amp;#8217;d already be cancelled.  Then we &lt;strong&gt;sendReceipt&lt;/strong&gt; and &lt;strong&gt;updatePaidStatus&lt;/strong&gt; in parellel with the use of &lt;strong&gt;compose_p&lt;/strong&gt;*.
&lt;br/&gt;&lt;br/&gt;

And perhaps, we&amp;#8217;d also like to parallelize the whole charge process itself.  Instead of a manual, imperative loop, we can use the declarative abstraction for iteration.

Here&amp;#8217;s the imperative loop:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var results = [];

for(credit_card in credit_cards) {
  results.push(chargeCard(credit_card));
}

runReport(results);
&lt;/code&gt;&lt;/pre&gt;

And here&amp;#8217;s the declarative one:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
map_p(chargeCard, runReport, credit_cards);
&lt;/code&gt;&lt;/pre&gt;

In this case, we used &lt;strong&gt;map_p&lt;/strong&gt; instead of a normal &lt;strong&gt;map&lt;/strong&gt;.  This takes a function to run, a callback, and an array.
&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;People say I&amp;#8217;m just a dreamer&amp;#8230;&lt;/h3&gt;

So declarative programming says what should be done and lets the underlying code decide what to do.  Imperative, order of execution style programming has a funny way of hindering that freedom. Like doing our own garbage collection in code, when we hard code these low level steps, we steal responsibility away from the compiler or interpreter or preprocessor or framework or language or other code or whatever and place it right in the middle of in our application.
&lt;br/&gt;&lt;br/&gt;

This has many benefits.  Perhaps, we should no longer fear &lt;em&gt;premature-optimization&lt;/em&gt; as much anymore.  Bug fixes can be made without touching your app.  Good people like the SQL folks can make their functions better and you don&amp;#8217;t have to change a single line to reap the benefits.

&lt;br/&gt;&lt;br/&gt;
Ladies and gentlemen, we&amp;#8217;ve risen to a higher level.  The dream of abstracting the world may be come true after all.

&lt;br/&gt;&lt;br/&gt;&lt;small&gt;* The &lt;strong&gt;compose_p&lt;/strong&gt; function uses setTimeout in my version on functional.js.  This works because I typically program javascript in the appcelerator titanium platform, which will thread on timeouts.  However, you can alter it to thread in many different strategies that work for you. &lt;/small&gt;&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/27774500328</link><guid>http://drboolean.tumblr.com/post/27774500328</guid><pubDate>Sun, 22 Jul 2012 11:32:00 -0700</pubDate></item><item><title>Functor, I hardly knew her!</title><description>&lt;p&gt;I&amp;#8217;m here!  I&amp;#8217;m at that special moment where I just realized why the heck functors matter.  At first I knew the types and I knew the ideas, I just didn&amp;#8217;t understand why it mattered.
&lt;br/&gt;&lt;br/&gt;
I think the root of my misunderstanding was my OO background and confusion about the job of types in the functional realm.  I&amp;#8217;m gonna write a post about that tomorrow, promise.
&lt;br/&gt;&lt;br/&gt;
The big revelation came when I was using flapjax (&lt;a href="http://flapjax-lang.org"&gt;flapjax-lang.org&lt;/a&gt;).  There is an object called Behavior that holds a value.  To run a normal function on that value, you have to call &lt;strong&gt;liftB&lt;/strong&gt;.  That will then pull the value out of the behavior, run your function with it, then put it back in.  Like this:
&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var myBehavior = new Behavior("Jimmy");
var updateUI = function(name){ $("#username").text(name) }
var newBehavior = liftB(updateUI, myBehavior);
&lt;/code&gt;&lt;/pre&gt;
Flapjax is awesome, but nevermind that right now - the details aren&amp;#8217;t important.  The important part is that the Behavior is actually a Functor.  And &lt;strong&gt;liftB&lt;/strong&gt; should just be &lt;strong&gt;fmap&lt;/strong&gt;.
&lt;br/&gt;&lt;br/&gt;
This blew my mind because I realized how many things out there are actually functors.  Let&amp;#8217;s dig in and then maybe look back at this code and hopefully you can see what I mean (if i do a good job of explaining it).
&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;So what&amp;#8217;s up with Functors?&lt;/h3&gt;
Lets forget about the mathematical aspects for a bit.  And besides, I&amp;#8217;m not the guy to explain that anyways.
&lt;br/&gt;&lt;br/&gt;
What a functor does is let you run a normal function that expects a normal type, like a string or integer, with a &lt;strong&gt;fancy&lt;/strong&gt; type, like an object.  A nice way to say that is you &lt;strong&gt;map&lt;/strong&gt; a function over a type.
&lt;br/&gt;&lt;br/&gt;
Let&amp;#8217;s start with a brilliant example.
&lt;br/&gt;&lt;br/&gt;
We have an object/type that&amp;#8217;s called Observable.  I&amp;#8217;m using objects and types interchangeably here.
&lt;br/&gt;&lt;br/&gt;&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var Observable = function(x) {
  return {val: x};
}

var o_name = Observable("brian");
&lt;/code&gt;&lt;/pre&gt;

Admittedly, it&amp;#8217;s not that observable just yet.
&lt;br/&gt;&lt;br/&gt;
We&amp;#8217;d really like to run a normal function like &lt;strong&gt;reverse&lt;/strong&gt; on our brand new observable, but we&amp;#8217;ve stuck our string &amp;#8220;brian&amp;#8221; inside of this object and &lt;strong&gt;reverse&lt;/strong&gt; doesn&amp;#8217;t work on that object.  Enter &lt;strong&gt;fmap&lt;/strong&gt;.
&lt;br/&gt;&lt;br/&gt;&lt;strong&gt;fmap&lt;/strong&gt; is a universal name (just like &lt;strong&gt;map&lt;/strong&gt;) for mapping a function over a type.  I&amp;#8217;m guess it stands for function map or functor map.  Since functions are sometimes called maps in category theory, I guess function map would be redundant.  But anyways.
&lt;br/&gt;&lt;br/&gt;
Let&amp;#8217;s make our object a functor by giving it an &lt;strong&gt;fmap&lt;/strong&gt; implementation.
&lt;br/&gt;&lt;br/&gt;&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var Observable = function(x) {
  
  var fmap = function(f) {
    var new_val = f(x);
    if(new_val != x) fireEvent('changed!', {val: new_val, previous_val: x})
    return Observable(new_val);
  }
  
  return {val: x, fmap: fmap};
}
&lt;/code&gt;&lt;/pre&gt;


There we go.  Check it out.  So we take a function, and get &lt;strong&gt;new_val&lt;/strong&gt; by running it over our previous value (in this instance &amp;#8220;brian&amp;#8221;).  Then if the two values aren&amp;#8217;t the same, we fire an event that it was changed with some information passed along in the event about old and new values.  Finally, and this is the important part, we wrap our new value back in our Observable and viola!  we&amp;#8217;ve run a normal function on our type.
&lt;br/&gt;&lt;br/&gt;
Since fmap is kind of universal, we can define a nice function that will work on any functor instance (that is, any instance that implements fmap).
&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var fmap = function(f,o) {
  return o.fmap(f);
}
&lt;/code&gt;&lt;/pre&gt;

And our final code is this:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var o_name = Observable("brian");
fmap(reverse, o_name); // Observable("nairb")
&lt;/code&gt;&lt;/pre&gt;

And there you have it!
&lt;br/&gt;&lt;br/&gt;
Part of what&amp;#8217;s great about this is our ability to run normal everyday functions on our objects.  We needn&amp;#8217;t define the same old stuff from object to object as long as we implement a way to map (fmap) over it.  Another reason you&amp;#8217;ll want to wear your Functor pants to work tomorrow is that we&amp;#8217;ve got the ability to actually alter the functions behavior while running inside our object.
&lt;br/&gt;&lt;br/&gt;
Let&amp;#8217;s look at one more example.  It&amp;#8217;s our old friend &lt;strong&gt;Maybe&lt;/strong&gt;.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var Maybe = function(x) {
  var fmap = function(f) {
    return isFalsy(x) ? Maybe(null) : Maybe(f(x));
  }
  
  return {val: x, fmap: fmap};
}

//+ getProduct :: Number -&amp;gt; Maybe(Product)
var getProduct = compose(Maybe, db.find('products'));

//+ nameOfProduct :: Number -&amp;gt; Maybe(String)
var nameOfProduct = fmap(pluck('name'), getProduct);

nameOfProduct(3) // "hella t-shirt"

&lt;/code&gt;&lt;/pre&gt;

Here, if the product doesn&amp;#8217;t come back, we won&amp;#8217;t blow up when we read it&amp;#8217;s name.  &lt;strong&gt;Maybe&lt;/strong&gt; just checks to see if the value&amp;#8217;s there before it runs a function on it.
&lt;br/&gt;&lt;br/&gt;
What&amp;#8217;s more, we could make &lt;strong&gt;db.find&lt;/strong&gt; return a functor too. We could say the call itself is an instruction to get the record and by fmapping something over it, it will actually make the db call.
&lt;br/&gt;&lt;br/&gt;&lt;h3&gt;In conclusion&lt;/h3&gt;
We&amp;#8217;re really just abstracting function application.  Any object could be a functor, but you usually want to stick with a behavior type object with a single value.&lt;br/&gt;&lt;br/&gt;.

The technical term for this stuff is that we&amp;#8217;re &lt;strong&gt;lifting&lt;/strong&gt; a function into a &lt;strong&gt;computational context&lt;/strong&gt;.  That makes sense since the context can change the behavior of our normal functions.  In the case of &lt;strong&gt;Observable&lt;/strong&gt; it adds behavior by notifying the authorities of change.  In the case of &lt;strong&gt;Maybe&lt;/strong&gt; it might not run it at all.
&lt;br/&gt;&lt;br/&gt;
So the intuition is that you can run a normal function on the value(s) inside a &amp;#8220;container&amp;#8221; object or you can run a function in a particular context.
&lt;br/&gt;&lt;br/&gt;
There are some laws that you must follow.  Really you should just make sure that fmapping the identity function (function(x) { return x; }) is equal to just calling the identity function.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
  fmap(id) == id;
&lt;/code&gt;&lt;/pre&gt;

I guess the last thing I wanted to say was that a List is a functor.  fmap in the cast of list is just our beloved map function that runs a normal function on each element inside of the list.  So the container analogy works well here too.
&lt;br/&gt;&lt;br/&gt;
Well, that&amp;#8217;s all I&amp;#8217;ve got for now.  Goodnight sweet Tumblr.&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/25413244757</link><guid>http://drboolean.tumblr.com/post/25413244757</guid><pubDate>Mon, 18 Jun 2012 20:57:00 -0700</pubDate></item><item><title>Silly module tricks</title><description>&lt;p&gt;I&amp;#8217;d been jealous of a nice haskell feature, as I typically am, and thought I&amp;#8217;d try to get as close as I could with javascript, as I typically do.

The &amp;#8220;must have&amp;#8221; feature is the ability to mix in a module globally or qualify it with a name.

Suppose we have an Account module with two functions: &lt;strong&gt;sayName&lt;/strong&gt; and &lt;strong&gt;User&lt;/strong&gt;.  Here&amp;#8217;s the desired behavior:
&lt;br/&gt;&lt;br/&gt;&lt;em&gt;I can mix in all the exported functions to the global namespace&lt;/em&gt;


&lt;pre class="prettyprint"&gt;
&lt;code class="language-haskell"&gt;
import Accounts

introduce :: Name
introduce = sayName user
	where user = User "brian"
&lt;/code&gt;&lt;/pre&gt;

&lt;em&gt;Or I can qualify the name so nothing clashes namespacewise.&lt;/em&gt;

&lt;pre class="prettyprint"&gt;
&lt;code class="language-haskell"&gt;
import qualified Accounts as Accts

introduce :: Accts.Name
introduce = Accts.sayName user
	where user = Accts.User "brian"
&lt;/code&gt;&lt;/pre&gt;

Here&amp;#8217;s what I came up with in js:
&lt;br/&gt;&lt;br/&gt;&lt;em&gt;Qualified&lt;/em&gt;

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
require('./account').as('Acct');

var user = Acct.User('brian');
var introduction = Acct.sayName(user);
&lt;/code&gt;&lt;/pre&gt;

&lt;em&gt;or unqualified:&lt;/em&gt;

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
require('./account').as();

var user = User('brian');
var introduction = sayName(user);
&lt;/code&gt;&lt;/pre&gt;

The account module looks like this:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
require("./support/functional");
var installer = require('./support/installer');

var User = function(x) { return {name: x} }

var _getName = pluck('name');

var sayName = compose("'Hi my name is '+", _getName);

installer.exports(module, {User: User, sayName: sayName});
&lt;/code&gt;&lt;/pre&gt;


I&amp;#8217;m always looking for something cleaner so let me know if you find it!
&lt;br/&gt;&lt;br/&gt;
*EDIT:

Here&amp;#8217;s installer.js

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var exports = function(mod, obj) {
  var GLOBAL = (typeof(window) == 'undefined') ? global : window;
  
  mod.exports = {
    as: function(name) {
      var target;
      
      if(name) {
        target = GLOBAL[name] = {};
      } else {
        target = GLOBAL;
      }
      
      for(k in obj) target[k] = obj[k];
    }
  }
}

module.exports = {exports: exports}
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/25295936340</link><guid>http://drboolean.tumblr.com/post/25295936340</guid><pubDate>Sun, 17 Jun 2012 08:47:00 -0700</pubDate></item><item><title>Sweet!  They filmed me jabbin’</title><description>&lt;iframe width="400" height="225" src="http://www.youtube.com/embed/HAcN3JyQoyY?wmode=transparent&amp;autohide=1&amp;egm=0&amp;hd=1&amp;iv_load_policy=3&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;showsearch=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;Sweet!  They filmed me jabbin’&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/22934900961</link><guid>http://drboolean.tumblr.com/post/22934900961</guid><pubDate>Sat, 12 May 2012 17:01:00 -0700</pubDate><category>functional programming</category><category>javascript</category></item><item><title>Everybody loves monads</title><description>&lt;p&gt;I made a monad library for javascript.  I&amp;#8217;m hosting it here &lt;a href="https://github.com/DrBoolean/MonadsJs"&gt;&lt;a href="https://github.com/DrBoolean/MonadsJs"&gt;https://github.com/DrBoolean/MonadsJs&lt;/a&gt;&lt;/a&gt;.

&lt;strong&gt;**This was a monad library based on the one for clojure since we weren&amp;#8217;t using types in js.  Since then I&amp;#8217;ve updated the library to use objects as types so while the examples here still have the same outcome, they don&amp;#8217;t work the same way anymore and the api is different.&lt;/strong&gt;

A great way to learn about monads is to watch &lt;a href="http://ndc2011.macsimum.no/mp4/Day2%20Thursday/Track6%201500-1600.mp4"&gt;Bob Martin&amp;#8217;s talk&lt;/a&gt;.

Let&amp;#8217;s look at a few built in ones first.  I wouldn&amp;#8217;t worry about the mechanics so much, but rather the functionality you gain with these puppies.

&lt;h2&gt;MaybeM&lt;/h2&gt;
Here&amp;#8217;s the &lt;strong&gt;maybeM&lt;/strong&gt; monad:
&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
maybeM = defMonad({
  mResult: id,
  mBind: function(mv, f) {
    return mv ? f(mv) : null;
  }
})
&lt;/code&gt;&lt;/pre&gt;

Let&amp;#8217;s see what it can do&amp;#8230;

Let&amp;#8217;s pretend we&amp;#8217;re in the admin section of some sexy &lt;span style="text-decoration:line-through;"&gt;backbone&lt;/span&gt; meteor ecommerce app.  If we wanted to print the name of a customer attached to a cart we could define a function like this:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var getCustomerName = compose('.name', '.customer', '.order');

// and the calling code:
var cart = { order: { customer: { name : "Bob Jones" } } };
getCustomerName(cart); // "Bob Jones"
&lt;/code&gt;&lt;/pre&gt;

Yes yes, demeter wept, I know.  But every once and a while you need a function like this.

But what if there is no customer attached yet.  Or order even?

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var cart = { };
getCustomerName(cart); // TypeError: Cannot read property 'customer' of undefined
&lt;/code&gt;&lt;/pre&gt;

We&amp;#8217;d have to do some crazy crap like this:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var getCustomerName = function(cart) {
  if(cart.order &amp;amp;&amp;amp; cart.order.customer) return cart.order.customer.name;
}
&lt;/code&gt;&lt;/pre&gt;

Yuck!  MaybeM to the rescue!

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var getCustomerName = compose(liftM(maybeM, compose('.name','.customer')), '.order');

// calling...
var cart = { };
getCustomerName(cart); // null
&lt;/code&gt;&lt;/pre&gt;

What we&amp;#8217;ve done is made a new function on the fly with &lt;strong&gt;liftM(maybeM, compose(&amp;#8216;.name&amp;#8217;,&amp;#8217;.customer&amp;#8217;))&lt;/strong&gt; in the middle of our compose chain.  The function will not run if order is null!  &amp;#8220;Look ma, no null checks&amp;#8221;.

So if we don&amp;#8217;t care about the result we say it&amp;#8217;s &lt;em&gt;maybe&lt;/em&gt; there.  In technical terms, we&amp;#8217;ve attached a context to our value (attached a maybe context to our cart) and we &amp;#8220;lifted&amp;#8221; our function to work with that kind of value.

We could have used the alternate monad syntax of:

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var getCustomerName = maybeM(function(cart){
  order &amp;lt;- cart.order
  return order.customer.name;
});
&lt;/code&gt;
&lt;/pre&gt;

Same deal.  What&amp;#8217;s cool is you can do a &lt;strong&gt;liftM(maybeM, myFragileFunction)&lt;/strong&gt; where ever you want.  You can define a function like that or use it when you&amp;#8217;re calling it.  That makes working with null easy.

Let&amp;#8217;s look at a different example.
&lt;h2&gt;ListM&lt;/h2&gt;

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
listM = defMonad({
  mResult: function(x){
    return [x];
  },
  mBind: function(mv, f) { 
    return flatten(map(f, mv));
  }
});
&lt;/code&gt;&lt;/pre&gt;

The list monad is a little funky to use at first, but it is crazy useful.  It&amp;#8217;s just maps inside of maps.  Keeping with our ecomm example, we&amp;#8217;d like to display a dropdown of all the variations of each shirt and size.  Let&amp;#8217;s do that the hideous way first.
&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var shirts = ['"Mr. Bean" Shirt', '"I do what the voices in my head tell me" Shirt'];
var sizes = ["SM", "LG", "XL", "XXL"];

var makeOptions = function(){
  var result = [];
  for(var x=0;x&lt;shirts for y="0;y&amp;lt;sizes.length;y++" result return makeoptions sizes&gt;&lt;/shirts&gt;&lt;/code&gt;&lt;/pre&gt;

Calling it, we get something like:

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
[ '"Mr. Bean" ShirtSM',
  '"Mr. Bean" ShirtLG',
  '"Mr. Bean" ShirtXL',
  '"Mr. Bean" ShirtXXL',
  '"I do what the voices in my head tell me" ShirtSM',
  '"I do what the voices in my head tell me" ShirtLG',
  '"I do what the voices in my head tell me" ShirtXL',
  '"I do what the voices in my head tell me" ShirtXXL' ]
&lt;/code&gt;&lt;/pre&gt;

Let&amp;#8217;s do it the sexy way:
&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var makeOptions = liftM(listM, "+");

makeOptions(shirts, sizes);
&lt;/code&gt;&lt;/pre&gt;

Wow, right?!  Let&amp;#8217;s take a moment to imagine the horror of adding colors in the first example.  In our monadic one, nothing changes.  We just call it with a third list:

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var colors = ["red", "blue", "green", "yellow"];

makeOptions(shirts, sizes, colors);
&lt;/code&gt;&lt;/pre&gt;

Bitchin.  You may decide to use that to create a list of every permutation and sort it to find the best options.  You may also use it like this next example.

Our ecomm site is in dire need of some stats because stats are fun to program.  We want what products were purchased from a given set of users.

&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
var users = [{orders: [{items: [{name: "product A"}, {name: "product B"}]}]}, {orders: [{items: [{name: "product C"}]}]}];

var getStats = listM(function(users) {
  u &amp;lt;- users
  o &amp;lt;- u.orders
  i &amp;lt;- o.items
  return i.name;
});

getStats(users); // [ 'product A', 'product B', 'product C' ]
&lt;/code&gt;&lt;/pre&gt;

It may be hard to see from my contrived example, but each line is it&amp;#8217;s own map inside the line above that&amp;#8217;s map.  If you&amp;#8217;re familiar with list comprehensions it works just like that.

Let&amp;#8217;s write that out by hand just to see.

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var getStats = function(users) {
  return map(function(u){
    map(function(o){
      map(function(i) {
        return i.name;
      }, o.items);
    }, u.orders);
  }, users);
}
&lt;/code&gt;&lt;/pre&gt;

Now that we&amp;#8217;ve seen some built in ones.  Let&amp;#8217;s see how to make a monad.

&lt;h2&gt;DotM&lt;/h2&gt;
If we have our data type &amp;#8220;dots&amp;#8221; and we want to work with them as if they were numbers we can can define a dot monad

&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
dotM = defMonad({
  mResult: compose(join(""), repeat(".")),
  mBind: function(d, f)  {
    return f(d.length);
  }
});
&lt;/code&gt;&lt;/pre&gt;

The monad has two functions &lt;strong&gt;mResult&lt;/strong&gt; and &lt;strong&gt;mBind&lt;/strong&gt;.  The &lt;strong&gt;mResult&lt;/strong&gt; is first so let&amp;#8217;s talk about that first.
&lt;pre class="prettyprint"&gt;
&lt;code class="language-javascript"&gt;
compose(join(""), repeat("."))
&lt;/code&gt;&lt;/pre&gt;

The &lt;strong&gt;repeat&lt;/strong&gt; function usually takes two arguments: the thing to repeat and a number of times to repeat it.  Here it is being partially applied with &amp;#8220;.&amp;#8221; so it&amp;#8217;s just waiting for it&amp;#8217;s number and it will return an array of .&amp;#8217;s

After that, we &lt;strong&gt;join&lt;/strong&gt; the array and get a string of dots.  Easy breezy.

For the the &lt;strong&gt;mBind&lt;/strong&gt; we make a function that first takes it&amp;#8217;s dots, then it&amp;#8217;s function and calls the function on the length of the dots.  That effectively converts the dots into numbers for our function to use.

So let&amp;#8217;s see it in action.
&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;

var divideDots = dotM(function(da, db) {
  a &amp;lt;- da
  b &amp;lt;- db
  return a / b;
});

divideDots("....", "..");  // 2
&lt;/code&gt;&lt;/pre&gt;

The left arrow kind of &amp;#8220;pulls&amp;#8221; the number value out of the dot value.  Then we just divide knowing that &lt;strong&gt;a&lt;/strong&gt; and &lt;strong&gt;b&lt;/strong&gt; are just numbers.

You can also &amp;#8220;lift&amp;#8221; a normal function that doesn&amp;#8217;t take dots into the dot monad.  So &lt;strong&gt;divide&lt;/strong&gt; works like a normal function, but we lift it and viola!  Divides dots.
&lt;pre class="prettyprint"&gt;
	&lt;code class="language-javascript"&gt;
var divide = function(a,b) {
  return a / b;
}

var divideDots = liftM(dotM, divide);

divideDots("....", "..");  // 2
&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/22931913747</link><guid>http://drboolean.tumblr.com/post/22931913747</guid><pubDate>Sat, 12 May 2012 16:07:00 -0700</pubDate><category>monad</category><category>functional programming</category><category>software development</category><category>javascript</category></item><item><title>Partial Application</title><description>&lt;p&gt;My dad once told me there are some things in this world that you can live without&amp;#8230;until you get them.  This is a truism that gets truer for me every year.  I think it has something to do with better technology.  Take for instance, an iphone or spotify or streaming netflix.  In my dad&amp;#8217;s case he was talking about a microwave.  Generation gap!

Anyways, partial application is one of those things.  I certainly use it more than my microwave, and i microwave tons of junk, daily.

So what is it?  Well, it&amp;#8217;s exactly how it sounds:  Applying a function partially.  Partially in terms of arguments.

If have a function that takes, say 3 arguments, we can give it 1 or 2 and get back a new function that only takes it&amp;#8217;s remaining arguments.  Kind of like &amp;#8220;preloading&amp;#8221; it with a few or all of it&amp;#8217;s arguments.  Let&amp;#8217;s take a looksee.

&lt;pre class="prettyprint lang-javascript"&gt;
var sumOfThree = function(a,b,c) {
  return a + b + c;
};

var needsTwoMoreArgs = sumOfThree.partial(20);
var justNeedsOneMore = needsTwoMoreArgs.partial(30);
justNeedsOneMore(10); // 60
&lt;/pre&gt;

Here, there&amp;#8217;s a function &lt;strong&gt;sumOfThree&lt;/strong&gt; that will take 3 arguments and add them together.  We begin by giving it it&amp;#8217;s first argument, which will return a brand new function that we&amp;#8217;ve name &lt;strong&gt;needsTwoMoreArgs&lt;/strong&gt;.  Indeed, it does only need two args to complete the call.  &lt;strong&gt;needsTwoMoreArgs&lt;/strong&gt; has stored it&amp;#8217;s first argument &lt;strong&gt;20&lt;/strong&gt; and can&amp;#8217;t wait to get the others.  Here&amp;#8217;s a conceptual representation of that:

&lt;pre class="prettyprint lang-javascript"&gt;
function(b,c) {
  return 20 + b + c;
};
&lt;/pre&gt;

So next we partially apply it yet again with &lt;strong&gt;30&lt;/strong&gt; and name the resulting function &lt;strong&gt;justNeedsOneMore&lt;/strong&gt;.  We call &lt;strong&gt;justNeedsOneMore&lt;/strong&gt; with &lt;strong&gt;10&lt;/strong&gt; and finally get a result!

We can apply as many as a time as we like:
&lt;pre class="prettyprint lang-javascript"&gt;
// two at a time
var justNeedsOneMore = sumOfThree.partial(20, 30);
justNeedsOneMore(10); // 60

// or all three!
var doesntNeedAnyArgs = sumOfThree.partial(20, 30, 10);
doesntNeedAnyArgs(); // 60
&lt;/pre&gt;

Wicked awesome.  One thing to note before we go any further.  The &lt;strong&gt;partial&lt;/strong&gt; function is not built into vanilla javascript.  We&amp;#8217;re using &lt;a href="http://osteele.com/sources/javascript/functional/"&gt;osteel&amp;#8217;s lib&lt;/a&gt; to grab this behavior.

Something else you can do is give it an underscore as a placeholder.

&lt;pre class="prettyprint lang-javascript"&gt;
var makeBobsName = sumOfThree.partial("Bob", _, "Smith");
makeBobsName("M."); // Bob M. Smith
&lt;/pre&gt;

&lt;h2&gt;Currying&lt;/h2&gt;

Currying is a technique where you return a new function for each argument that&amp;#8217;s called - in effect partially applying it each time.  So if we have a curried function we don&amp;#8217;t have to explicitly call &lt;strong&gt;partial&lt;/strong&gt; each time.  In haskell, each function is defaulted to this behavior.  I&amp;#8217;ve made a little wrapper &lt;strong&gt;defn&lt;/strong&gt; that will do that for your functions as well.  It lives in my fork of osteele&amp;#8217;s lib &lt;a href="https://github.com/DrBoolean/Functional-Javascripts"&gt;&lt;a href="https://github.com/DrBoolean/Functional-Javascripts"&gt;https://github.com/DrBoolean/Functional-Javascripts&lt;/a&gt;&lt;/a&gt;.  Let&amp;#8217;s play with that!

&lt;pre class="prettyprint lang-javascript"&gt;
var sumOfThree = defn(function(a,b,c) {
  return a + b + c;
});

var justNeedsOne = sumOfThree("hell", "o ");
justNeedsOne("world"); // hello world

map(sumOfThree(1,2), [3,4,5,6]);  // [ 6, 7, 8, 9 ]

var sum = reduce("+", 0);
sum([1,2,3,4]); // 10

var getVowels = filter(match(/[aeiou]/ig));
getVowels("so many vowels!"); // [ 'o', 'a', 'o', 'e' ]
&lt;/pre&gt;

The last example is particularly cool.  It partially applies match and filter.   We&amp;#8217;ve done 2 things to be able to write code like this.  The first was to make a function called &lt;strong&gt;match&lt;/strong&gt; that takes it&amp;#8217;s regular expression first and it&amp;#8217;s string second.  Then we wrapped in a &lt;strong&gt;defn&lt;/strong&gt;.

&lt;pre class="prettyprint lang-javascript"&gt;
match = defn(function(expr, x) { return x.match(expr); });
&lt;/pre&gt;

The string as the second argument allows us to partially apply it without knowing what the data that we&amp;#8217;re operating on will be.  We&amp;#8217;re effectively &lt;strong&gt;Separating our data from our functions&lt;/strong&gt;.  That makes for really generic code since we have general functions waiting for whatever data they get rather than first have the data and calling functions on it.  It&amp;#8217;s no coincidence that the &lt;strong&gt;map&lt;/strong&gt;, &lt;strong&gt;filter&lt;/strong&gt;, and &lt;strong&gt;reduce&lt;/strong&gt; functions take their data second either.

This wrapping of native functions isn&amp;#8217;t really hard to do.  It&amp;#8217;s pretty much the same thing each time.  I&amp;#8217;ve pretty much wrapped all the native functions i normally use (there really wasn&amp;#8217;t all that much) and put them on my github in a lib called the &lt;a href="https://github.com/DrBoolean/Functional-Javascripts/blob/master/prelude.js"&gt;prelude&lt;/a&gt;.  Now we can code like the wild animals we are!  But really, I haven&amp;#8217;t had any performance issues or namespace collisions so far.  We can take it one step further and split them out to mix in appropriately when needed or even pass some argument to qualify the names, but for now, I&amp;#8217;m building production apps daily without worry so if it ain&amp;#8217;t broke&amp;#8230;

In the end, partial application is okay on it&amp;#8217;s own, but really shines when using together with &lt;strong&gt;compose&lt;/strong&gt;.  This can help you fix up arguments so functions compose better&amp;#8230;or at all.  When we start matching those two up together we get a powerful combination that proves more useful than a microwave.&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/22931848110</link><guid>http://drboolean.tumblr.com/post/22931848110</guid><pubDate>Sat, 12 May 2012 16:06:00 -0700</pubDate><category>partial application</category><category>functional programming</category><category>javascript</category><category>software development</category></item><item><title>Tweet Grammer Fixer:  OO vs FP</title><description>&lt;p&gt;To play with what I&amp;#8217;ve been learning, I&amp;#8217;m going to make a OO vs Functional comparison.

The goal is to clean up tweet grammer.  The output should be something like:
&lt;pre class="prettyprint lang-javascript"&gt;
// Before
// "I'm tweeting like an animal but I keep missing punctuation. someone make me a tool.Then I can tweet like a scholar."
// After
// "I'm tweeting like an animal, but I keep missing punctuation. Someone make me a tool. Then I can tweet like a scholar."
&lt;/pre&gt;

&lt;table&gt;&lt;tr&gt;&lt;th&gt;
Object Oriented
&lt;/th&gt;
&lt;th&gt;
Functional
&lt;/th&gt;
&lt;/tr&gt;&lt;tr&gt;&lt;td class="border-right"&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
var GrammerChecker = function(tweets) {
  this.tweets = tweets;
}

GrammerChecker.prototype = {
  check: function() {
    return this.tweets.map(function(t){
      var clean_tweet = new CleanTweet(t);
      return clean_tweet.clean();
    });
  }
}


var CleanTweet = function(tweet) {
  this.tweet = tweet;
}

CleanTweet.prototype = {
  clean: function() {
    this.commaBeforeBut();
    this.capitolAfterPeriod();
    this.spaceAfterPeriod();
    return this.tweet;
  },
  
  capitolAfterPeriod: function() {
    this.tweet.replace(/\.\s+([a-z])/g, function(word){ return word.toUpperCase(); });
  },
  
  spaceAfterPeriod: function() {
    this.tweet.replace(/(\w)\.(\w)/g, "$1. $2");
  },
  
  commaBeforeBut: function() {
    this.tweet.replace(/(\w+)[^,]but/gi, "$1, but");
  }
}

module.exports = GrammerChecker;

&lt;/pre&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
commaBeforeBut = replace(/(\w+)[^,]but/gi, "$1, but");

capitolAfterPeriod = replace(/\.\s+([a-z])/g, '.toUpperCase()'.lambda());

spaceAfterPeriod = replace(/(\w)\.(\w)/g, "$1. $2");

check = map(compose(spaceAfterPeriod, capitolAfterPeriod, commaBeforeBut));

module.exports = {check: check};

&lt;/pre&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;


And here&amp;#8217;s using it:


&lt;table&gt;&lt;tr&gt;&lt;th&gt;
Object Oriented
&lt;/th&gt;
&lt;th&gt;
Functional
&lt;/th&gt;
&lt;/tr&gt;&lt;tr&gt;&lt;td class="border-right"&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
var requester = require("../requester1");
var GrammerChecker = require("./grammer_check_oo");


requester.get("http://search.twitter.com/search.json", {q: "food"}, function(response){
  var json = JSON.parse(response);
  var tweets = json.results.map(function(r){ return r.text; });
  var checker = new GrammerChecker(tweets);
  var result = checker.check();
  console.log(result);
});

&lt;/pre&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
require('../functional');
var requester = require("../requester");
var GrammerCheck = require("./grammer_check_fun");

transform = compose(map('.text'), '.results', JSON.parse);
getTweets = requester.get("http://search.twitter.com/search.json", {q: "food"});
getTweets(compose(log, GrammerCheck.check, transform));

&lt;/pre&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;

To get this haskelly in javascript, I&amp;#8217;m using osteele&amp;#8217;s functional.js and a few function wrappers of my own.  The functional version of replace auto-currys and doesn&amp;#8217;t destroy the original string.

The helper libraries are &lt;a href="https://github.com/DrBoolean/Functional-Javascripts"&gt;Here&lt;/a&gt;

&lt;h2&gt;What i noticed&lt;/h2&gt;

After writing the example, I realized that the OO version wasn&amp;#8217;t very resuable due to my nomenclature.  If I rename &amp;#8220;tweet&amp;#8221; to &amp;#8220;sentence&amp;#8221;, i get a little library out of it.

I often try to rename things afterwards.  This plays a large part in cleaning up my code - generalize and extract everything possible into a lib, then implement with specific verbage in the app.

But for the functional side, due to pointfree style, I don&amp;#8217;t need to name anything anyways!  Done.

In fact, the functional side looks more like a libary than app code.  It&amp;#8217;s natural to write this way.

We could extend it pretty easily into functions that make dsl-like grammer checker.

&lt;pre class="prettyprint lang-javascript"&gt;
commaBefore = function(word) {
  return replace(new RegExp('(\\w+)[^,]'+word, 'gi'), "$1, "+word);
}
&lt;/pre&gt;

Now we can do things like this:

&lt;table&gt;&lt;tr&gt;&lt;th&gt;
Object Oriented
&lt;/th&gt;
&lt;th&gt;
Functional
&lt;/th&gt;
&lt;/tr&gt;&lt;tr&gt;&lt;td class="border-right"&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
// chaining by returning 'this'
var checker = new GrammerChecker(tweets);
checker.commaBefore("but").commaBefore("however").commaBefore("yet").result;

&lt;/pre&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
map(compose(commaBefore("but"), commaBefore("yet"), commaBefore("however")));

&lt;/pre&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;


But then when I want to say, compose the GrammerChecker with a HtmlEntities sanitizer so I can switch stuff like &amp;amp;quote; to &amp;#8220;, the result would probably be as follows:


&lt;table&gt;&lt;tr&gt;&lt;th&gt;
Object Oriented
&lt;/th&gt;
&lt;th&gt;
Functional
&lt;/th&gt;
&lt;/tr&gt;&lt;tr&gt;&lt;td class="border-right"&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
var checker = new GrammerChecker(tweets);
var cleaned_grammer = checker.commaBeforeBut("but").commaBefore("however").commaBefore("yet").result;
cleaned_grammer.map(function(cg){
	var entities = new HtmlEntities(cg);
	return entities.santize();
});

&lt;/pre&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;pre class="prettyprint lang-javascript"&gt;
var check = compose(commaBefore("but"), commaBefore("yet"), commaBefore("however"));
var getResult = map(compose(HtmlEntities.santize, check));
getResult(tweets);

&lt;/pre&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;


For OO, I have to create a new object, put the data in it so i can do stuff to that data, then do that stuff.

In FP, since we can compose functions or even programs together, we can just glue them both together and pipe our data through it.

&lt;h2&gt;So who wins?&lt;/h2&gt;

Which is better?  I&amp;#8217;ll leave that to the reader to decide, but I do have some things to note.
&lt;ul&gt;&lt;li&gt;
		Functional is a fraction of the size of code.  Distilled to just parts that matter.  OO requires a lot more ceremony to get started.
	&lt;/li&gt;
	&lt;li&gt;
		OO would be tricky to make parellel due to imperative instruction and destructive methods.
	&lt;/li&gt;
	&lt;li&gt;
		OO is rather black boxy during usage.  You see the tweets go in to the GrammerChecker, but don&amp;#8217;t know what&amp;#8217;s going on from there.  Then the check() method returns a result, which are hopefully the cleaned tweets, but it&amp;#8217;s not that obvious (probably my fault).
		This may seem kind of trivial here, but i think it&amp;#8217;s a huge deal when working with more complex examples.
		With Functional, you know the check function can only take an argument and return a result (as all functions in the paradigm do) and there&amp;#8217;s only 1 function call (no constructor) so it&amp;#8217;s pretty easy to see where the tweets go.
	&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/22930622966</link><guid>http://drboolean.tumblr.com/post/22930622966</guid><pubDate>Sat, 12 May 2012 15:44:00 -0700</pubDate><category>functional programming</category><category>object oriented</category><category>software development</category><category>javascript</category></item><item><title>Composition</title><description>&lt;p&gt;Composition is a fancy name for passing the result of one function as an argument into the next function.

If we have some functions like these:
&lt;pre class="prettyprint lang-javascript"&gt;

add2 = function(number) {
  return number + 2;
}

subtract1 = function(number) {
  return number - 1;
}
&lt;/pre&gt;


We &lt;em&gt;could&lt;/em&gt; do this:
&lt;pre class="prettyprint lang-javascript"&gt;

addSubtract = function(n) {
  var addedValue = add2(n);
  return subtract1(addedValue);
}
&lt;/pre&gt;


Or We could do &lt;em&gt;this&lt;/em&gt;:
&lt;pre class="prettyprint lang-javascript"&gt;

addSubtract = compose(subtract1, add2);
&lt;/pre&gt;


Both would yield 4:
&lt;pre class="prettyprint lang-javascript"&gt;

addSubtract(3);  // 4
&lt;/pre&gt;


compose makes a brand new function.  The data flows from right to left applying each function along the way.  Right to left makes sense when you think about the parenthesis going to the right of the newly constructed function.

Here&amp;#8217;s another few examples
&lt;pre class="prettyprint lang-javascript"&gt;

dasherize = compose(join('-'), split(/\s+/g);
dasherize("Big Al's Trucks"); // "Big-Al's-Trucks"

doFunkyThingsWithName = compose('.toUpperCase()', reverse, '.name')
doFunkyThingsWithName({name: "George"}); // "EGROEG"
&lt;/pre&gt;


The combination possibilities are endless.  We can compose groups of functions that go together into little programs.  Then we can even compose those programs!

Checkout how easy it is to play around:

&lt;pre class="prettyprint lang-javascript"&gt;

var loggingFun = compose(log, subtract1, log, add2);
loggingFun(3);
// 5
// 4
// 4

var memoizedFun = memoize(loggingFun);
memoizedFun(4);
// 6
// 5
// 5

memoizedFun(4);
// 5

var newProgram = compose(otherProgram, memoizedFun);

parallel_compose(thirdProgram, newProgram);

&lt;/pre&gt;


Why is this so amazing?

&lt;h3&gt;No data&lt;/h3&gt;

You may notice I don&amp;#8217;t need to name any intermediate results.  This is a big deal.  This assists in separating your data from your functions since you simply don&amp;#8217;t see the data.  I think a lot of people are turned off from functional programming by the thought of juggling arguments (data) around all the time instead of tucking them away in a nice object.  Here, there is no data at all, rather functions plugged together to work on anything.  This gives you &lt;strong&gt;megagenericicity&lt;/strong&gt; which is a word i just made up.  Starting from the original data call, we just start composing away.

&lt;pre class="prettyprint lang-javascript"&gt;

UsersController = (function(){
  index = db.all('users', compose(renderView, manipulateUserData));

  return {index: index}
})();
&lt;/pre&gt;


&lt;h3&gt;Build up from smaller functions&lt;/h3&gt;

Is it a surprise to find out most of what you write is the same stuff over and over again?  Instead of writing out the same function calls with different names or the same assignment statements to different variables, you can skip all of that and just drop the function name in. The code drops in size, becomes more generic, and you distill the code to just the important behavior.  If you&amp;#8217;re worried about names missing since names give you an idea of what we&amp;#8217;re operating on, don&amp;#8217;t sweat it - just assign a specific name to each function:

&lt;pre class="prettyprint lang-javascript"&gt;

// no one says it has to be like this:
getArgNames = compose(last, match(/\((.*)\)/), first, split('\n'));

// it can easily be like this:
firstLine = compose(first, split('\n'));
contentInsideParenthesis = compose(last, match(/\((.*)\)/));
getArgNames = compose(contentInsideParenthesis, firstLine);
&lt;/pre&gt;


Smaller functions that do one thing means more reusable parts.  Taking advantage of the divide and conquer strategy, we can build very complex systems with easy to grok simple functions.

Turns out, lots of the smaller functions you break out can be put in to utility libraries and moved out of your application code.  This technique promotes reusability (common theme here&amp;#8230;) and makes your app simpler.

&lt;h3&gt;Declarative Programming&lt;/h3&gt;

In declarative programming, we tell the computer what to do and let it accomplish the task however it sees fit.  Think of SQL.  You express a query as a single expression and let the computer do it&amp;#8217;s job.  The SQL folks can make the compiler better and better and you don&amp;#8217;t have to change a single line.  Imperative, order of execution style programming has a funny way of hindering that freedom.  Like doing our own garbage collection in code, when we hard code these low level steps, we steal responsibility away from the compiler/interpreter and place it in our application.

Also, one expression can be manipulated much easier than several lines of separate steps: you simply copy and paste little chunks of code around.  Want logging?  Add an extra function in the chain.  etc.

When we program like this, our application code likely won&amp;#8217;t need to change when we optimize.  We can fix bugs in our underlying functions, but the statement of what needs to happend doesn&amp;#8217;t change.  Ladies and gentlemen, we&amp;#8217;ve risen to a higher level.

&lt;h3&gt;Free Dsl&lt;/h3&gt;

Don&amp;#8217;t actually &lt;em&gt;do&lt;/em&gt; anything!  Just say it and let the other stuff do the work.  Brilliant.&lt;/p&gt;</description><link>http://drboolean.tumblr.com/post/22917285496</link><guid>http://drboolean.tumblr.com/post/22917285496</guid><pubDate>Sat, 12 May 2012 11:55:00 -0700</pubDate><category>composition</category><category>functional programming</category><category>javascript</category><category>software development</category></item></channel></rss>
