tag:blogger.com,1999:blog-74687416324267669832017-06-22T08:02:04.834+05:30Functional JavaScriptEach post will cover a specific aspect of functional programming in JavaScript.Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.comBlogger6125tag:blogger.com,1999:blog-7468741632426766983.post-90944327322391712292013-07-25T14:23:00.000+05:302013-07-25T14:47:47.766+05:30Monads<h1 id="monads">Monads</h1> <p>All the code for this post are available here.<a href="https://github.com/santoshrajan/monadjs">https://github.com/santoshrajan/monadjs</a></p> <p>Consider the <code>map</code> functor from the last chapter. We could use <code>map</code> to iterate over two arrays adding each element of the first to the second.</p> <pre><code>var result = [1, 2].map(function(i) {<br /> return [3, 4].map(function(j) {<br /> return i + j<br /> })<br />})<br />console.log(result) ==>> [ [ 4, 5 ], [ 5, 6 ] ]<br /></code></pre> <p>The type signature of the inner function is</p> <pre><code>f: int -> int<br /></code></pre> <p>and the type signature of the inner <code>map</code> is</p> <pre><code>map: [int] -> [int]<br /></code></pre> <p>The type signature of the outer function is</p> <pre><code>f: int -> [int]<br /></code></pre> <p>and the type signature of the outer <code>map</code> is</p> <pre><code>map: [int] -> [[int]]<br /></code></pre> <p>This is the right behaviour you would expect from a functor. But this is not what we want. We want the result to be flattened like below.</p> <pre><code>[ 4, 5, 5, 6 ]<br /></code></pre> <h2 id="arraymonad">Array Monad</h2> <p>For that to happen, the type signature of a functor should always be restricted to</p> <pre><code>F: [int] -> [int]<br /></code></pre> <p>But functors do not place any such restriction. But <code>monads</code> do. The type signature of an array monad is</p> <pre><code>M: [T] -> [T]<br /></code></pre> <p>where <code>T</code> is a given type. That is why <code>map</code> is a functor but not a monad. That is not all. We have to put some type restriction on the function passed it too. The function cannot return any type it likes. We can solve this problem by restricting the function to return the <code>Array</code> type. So the function's type signature is restricted to</p> <pre><code>f: T -> [T]<br /></code></pre> <p>This function is known as <code>lift</code>, Because it lifts the type to the required type. This is also known as the <code>monadic function</code>. And the original value given to the monad is known as the <code>monadic value</code>. Here is the arrayMonad.</p> <pre><code>function arrayMonad(mv, mf) {<br /> var result = []<br /> mv.forEach(function(v) {<br /> result = result.concat(mf(v))<br /> })<br /> return result<br />}<br /></code></pre> <p>Now we can use the array monad to do our first calculation.</p> <pre><code>console.log(arrayMonad([1,2,3], function(i) {<br /> return [i + 1]<br />})) ==>> [ 2, 3, 4 ]<br /></code></pre> <p>Notice that our monadic function wraps the result in an array <code>[i + 1]</code>. Now let us try it with the two dimensional problem we started with.</p> <pre><code>var result = arrayMonad([1, 2], function(i) {<br /> return arrayMonad([3, 4], function(j) {<br /> return [i + j]<br /> })<br />})<br />console.log(result) ==>> [ 4, 5, 5, 6 ]<br /></code></pre> <p>Now we begin to see the power of monads over functors.</p> <p>We can write a generic two dimensional iterator for arrays which will take two arrays and a callback, and call it for each element of both arrays.</p> <pre><code>function forEach2d(array1, array2, callback) {<br /> return arrayMonad(array1, function(i) {<br /> return arrayMonad(array2, function(j) {<br /> return [callback(i,j)]<br /> })<br /> })<br />}<br /></code></pre> <p>And we can try this function</p> <pre><code>forEach2d([1, 2], [3,4], function(i, j) {<br /> return i + j<br />}) ==>> [ 4, 5, 5, 6 ]<br /></code></pre> <p>Notice that the callback function is just a regular function, so we had to <code>lift</code> its return value <code>[callback(i,j)]</code> to an array. However all monads define a function to do the <code>lifting</code>. Its called <code>mResult</code>. We will add <code>mResult</code> to the arrayMonad function object. Also the <code>concat</code> function is inneficient as it creates a new array everytime. We will apply array <code>push</code> instead. Here is the final code for the array monad.</p> <pre><code>function arrayMonad(mv, mf) {<br /> var result = []<br /> mv.forEach(function(v) {<br /> Array.prototype.push.apply(result, mf(v))<br /> })<br /> return result<br />}<br /><br />arrayMonad.mResult = function(v) {<br /> return [v]<br />}<br /></code></pre> <p>and rewrite <code>forEach2d</code></p> <pre><code>function forEach2d(array1, array2, callback) {<br /> return arrayMonad(array1, function(i) {<br /> return arrayMonad(array2, function(j) {<br /> return arrayMonad.mResult(callback(i,j))<br /> })<br /> })<br />}<br /></code></pre> <p>As an exersice I will leave it to the reader to implement <code>forEach3d</code>.</p> <p>The arrayMonad is a monadic function and is otherwise known as <code>bind</code> or <code>mbind</code>. For a function to be a monad it must define atleast the functions <code>mbind</code> and <code>mresult</code>.</p> <h2 id="identitymonad">Identity Monad</h2> <p>The identity monad is the simplest of all monads, named so because it's <code>mresult</code> is the identity function.</p> <pre><code>function indentityMonad(mv, mf) {<br /> return mf(mv)<br />}<br /><br />identityMonad.mResult = function(v) {<br /> return v<br />}<br /></code></pre> <p>It is not a very useful monad. But it is a valid monad.</p> <h2 id="maybemonad">Maybe Monad</h2> <p>The maybe Monad is similar to the identity monad, except that it will not call the monadic function for values <code>null</code> or undefined. In fact it boild down to the same <code>mayBe</code> functor we saw in the last chapter.</p> <pre><code>function mayBeMonad(mv, mf) {<br /> return mv === null || mv === undefined || mv === false ? null : mf(mv)<br />}<br /><br />mayBeMonad.mResult = function(v) {<br /> return v<br />}<br /></code></pre> <h2 id="themonadlaws">The Monad Laws</h2> <p>The First Monad Law</p> <pre><code>M(mResult(x), mf) = mf(x)<br /></code></pre> <p>Which means whatever <code>mResult</code> does to <code>x</code> to turn <code>x</code> into a monadic value, <code>M</code> will unwrap that monadic value before applying it to monadic function <code>mf</code>. Let us test this on our array monad.</p> <pre><code>var x = 4; <br />function mf(x) { <br /> return [x * 2] <br />}<br />arrayMonad(arrayMonad.mResult(x), mf) ==>> [ 8 ]<br />mf(x) ==>> [ 8 ]<br /></code></pre> <p>The Second Monad Law</p> <pre><code>M(mv, mResult) = mv<br /></code></pre> <p>Which means whatever <code>mBind</code> does to extract <code>mv</code>'s value, <code>mResult</code> will undo that and turn the value back to a monadic value. This ensures that <code>mResult</code> is a monadic function. Let us test it. This is equivalent to the preserve identity case of the functor.</p> <pre><code>arrayMonad([1, 2, 3], arrayMonad.mResult) ==>> [ 1, 2, 3 ]<br /></code></pre> <p>The Third Monad Law</p> <pre><code>M(M(mv, mf), mg)) = M(mv, function(x){return M(mf(x), mg)})<br /></code></pre> <p>What this is saying is that it doesn't matter if you apply <code>mf</code> to <code>mv</code> and then to <code>mg</code>, or apply <code>mv</code> to a monadic function that is a composition of <code>mf</code> and <code>mg</code>. Let us test this.</p> <pre><code>function mg(x) {<br /> return [x * 3]<br />}<br />arrayMonad(arrayMonad([1, 2, 3], mf), mg) ==>> [ 6, 12, 18 ]<br />arrayMonad([1, 2, 3], function(x) {<br /> return arrayMonad(mf(x), mg)<br />}) ==>> [ 6, 12, 18 ]<br /></code></pre> <h2 id="domonad">doMonad</h2> <p>We know that a monadic function takes a value and returns a monadic value. A monad takes a monadic value and a monadic function and returns a monadic value. What if a monadic function calls a monad with a monadic value and itself and returns the result? That would be a valid monadic function because it returns a monadic value.</p> <p>The function <code>doMonad</code> does exactly this. It takes a <code>monad</code> and an array of monadic values and a callback as its arguments. It defines a monadic function that recursively calls the monad with each monadic value and itself. It breaks out of the loop when there are no more monadic values left. It returns the <code>callback</code> called with each unwrapped value of the monadic value. The callback <code>cb</code> is curried in a closure called <code>wrap</code> and is visible to <code>mf</code>. The curry function is from the chapter on currying.</p> <pre><code>function curry(fn, numArgs) {<br /> numArgs = numArgs || fn.length<br /> return function f(saved_args) {<br /> return function() {<br /> var args = saved_args.concat(Array.prototype.slice.call(arguments))<br /> return args.length === numArgs ? fn.apply(null, args) : f(args)<br /> }<br /> }([])<br />}<br /><br />function doMonad(monad, values, cb) {<br /> function wrap(curriedCb, index) {<br /> return function mf(v) {<br /> return (index === values.length - 1) ?<br /> monad.mResult(curriedCb(v)) :<br /> monad(values[index + 1], wrap(curriedCb(v), index + 1))<br /> }<br /> }<br /> return monad(values[0], wrap(curry(cb), 0)) <br />}<br />doMonad(arrayMonad, [[1, 2], [3, 4]], function(x, y) {<br /> return x + y<br />}) //==>> [ 4, 5, 5, 6 ]<br /></code></pre> <p>We don't need the <code>forEach2d</code> function we wrote earlier! And the best is yet to come!</p> <h2 id="arraycomprehensionusingdomonad">Array comprehension using doMonad</h2> <p>We can write a generic array comprehension function called <code>FOR</code> which takes a set of arrays and a callback in its arguments.</p> <pre><code>function FOR() {<br /> var args = [].slice.call(arguments)<br /> callback = args.pop()<br /> return doMonad(arrayMonad, args, callback)<br />}<br /><br />FOR([1, 2], [3, 4], function(x, y) {<br /> return x + y<br />}) //==>> [ 4, 5, 5, 6 ]<br />FOR([1, 2], [3, 4], [5, 6], function(x, y, z) {<br /> return x + y + z<br />}) //==>> [ 9, 10, 10, 11, 10, 11, 11, 12 ]<br /></code></pre> <p>How awesome is that!</p> <h2 id="statemonad">State Monad</h2> <p>In the last chapter on functors we saw function fucntor that takes a value of type <code>function</code>. Similarly monadic values can also be functions. However it is important to distinguish between monadic functions and monadic values that are functions. The type signature of a monadic function is</p> <pre><code>mf: v -> mv<br /></code></pre> <p>ie. takes a value and lifts it to a monadic value. Note that the monadic value itself is a function. So <code>mf</code> will return a function <code>mv</code>.</p> <p>The type signature of a monadic value which is a function depends on whatever that function is doing as the case may be. In the case of the state monad the type signature of its monadic value is</p> <pre><code>mv: state -> [value, new state]<br /></code></pre> <p>The monadic value function takes a <code>state</code> and returns an array containing a value and a new state. The <code>state</code> can be of any type array, string, integer, anything.</p> <p>The <code>stateMonad</code> takes a monadic value and a monadic function and returns a function to which we have to pass the initial state. The initial state is passed <code>mv</code> which returns a value. <code>mf</code> is then called with this value and <code>mf</code> returns a monadic value which is a function. We must call this function with the <code>newstate</code>. Phew!</p> <pre><code>function stateMonad(mv, mf) { <br /> return function(state) { <br /> var compute = mv(state) <br /> var value = compute[0] <br /> var newState = compute[1] <br /> return mf(value)(newState) <br /> } <br />}<br /></code></pre> <p>And <code>mResult</code> for the state monad is</p> <pre><code>stateMonad.mResult = function(value) { <br /> return function(state) { <br /> return [value, state]; <br /> } <br />}<br /></code></pre> <h2 id="parsermonad">Parser Monad</h2> <p>A parser is function that takes a string matches the string based on some criteria and returns the matched part and the remainder. Lets write the type signature of the function.</p> <pre><code>parser: string -> [match, newstring]<br /></code></pre> <p>This looks like the monadic value of the state monad, with <code>state</code> restricted to the type string. But thats not all, the parser will return <code>null</code> if the string did not match the criteria. So lets write the parser monad to reflect the changes.</p> <pre><code>function parserMonad(mv, mf) { <br /> return function(str) { <br /> var compute = mv(str)<br /> if (compute === null) {<br /> return null<br /> } else {<br /> return mf(compute[0])(compute[1])<br /> } <br /> } <br />}<br /><br />parserMonad.mResult = function(value) { <br /> return function(str) { <br /> return [value, str]; <br /> } <br />}<br /></code></pre> <p>As we saw earlier Monads require you to define atleast two functions, <code>mBind</code> (the monad function itself) and <code>mResult</code>. But that is not all. Optionally you can define two more functions, <code>mZero</code> and <code>mPlus</code>.</p> <p><code>mZero</code> is the definition of "Nothing" for the monad. eg. for the <code>arrayMonad</code>, <code>mZero</code> would be <code>[]</code>. In the case of the parser monad <code>mZero</code> is defined as follows. (mZero must have the same type signature of the monadic value).</p> <pre><code>parserMonad.mZero = function(str) {<br /> return null<br />}<br /></code></pre> <p><code>mPlus</code> is a function that takes monadic values as its arguments, and ignores the <code>mZero</code>'s among them. How the accepted values are handled depends on the individual monad. For the parser monad, <code>mZero</code> will take a set of parsers (parser monad's monadic values) and will return the value returned by the first parser to return a non <code>mZero</code> (null) value.</p> <pre><code>parserMonad.mPlus = function() {<br /> var parsers = Array.prototype.slice.call(arguments)<br /> return function(str) {<br /> var result, i<br /> for (i = 0; i < parsers.length; ++i) {<br /> result = parsers[i](str)<br /> if (result !== null) {<br /> break;<br /> }<br /> }<br /> return result<br /> }<br />}<br /></code></pre> <h2 id="continuationmonad">Continuation Monad</h2> <p>The continuation monad takes a bit to understand. In the chapter on function composition we saw that the composition of two functions <code>f</code> and <code>g</code> is given by</p> <pre><code>(f . g) = f(g(x))<br /></code></pre> <p><code>f</code> is known as the continuation of <code>g</code>.</p> <p>We also know that we can wrap values in a function by creating a closure. In the example below the inner function has a <code>value</code> wrapped in its closure.</p> <pre><code>function(value) {<br /> return function() {<br /> // value can be accessed here<br /> }<br />} <br /></code></pre> <p>The monadic value of a continuation monad, is a function that takes a continuation function and calls the continuation with its wrapped value. This is just like the inner function above called with a continuation function and we we can write it as</p> <pre><code>function(continuation) {<br /> return continuation(value)<br />}<br /></code></pre> <p>The <code>mResult</code> function of monad takes a value and <code>lifts</code> it to a monadic value. So we can write the <code>mResult</code> function for the continuation monad.</p> <pre><code>var mResult = function(value) {<br /> return function(continuation) {<br /> return continuation(value)<br /> }<br />}<br /></code></pre> <p>So <code>mResult</code> is a function that takes a value, returns a monadic value which you call with a continuation.</p> <p>The continuation monad itself or <code>mBind</code> is more complicated.</p> <pre><code>var continuationMonad = function(mv, mf) {<br /> return function(continuation) {<br /> // we will add to here next<br /> }<br />}<br /></code></pre> <p>First it will return a function you need to call with a continuation. Thats easy. But how can it unwrap the value inside <code>mv</code>? <code>mv</code> accepts a continuation, but calling <code>mv</code> with the continuation will not do. We need to unwrap the value in <code>mv</code> and call <code>mf</code> first. So we need to trick <code>mv</code> into giving us the value first by calling it with our own continuation thus.</p> <pre><code>mv(function(value) {<br /> // gotcha! the value<br />})<br /></code></pre> <p>We can add this function to the code above.</p> <pre><code>var continuationMonad = function(mv, mf) {<br /> return function(continuation) {<br /> return mv(function(value) {<br /> // gotcha! the value<br /> })<br /> }<br />}<br /></code></pre> <p>Now all we have to do is call <code>mf</code> with the value. We know a monadic function takes a value and returns a monadic value. So we call the returned monadic value from <code>mf</code> with the continuation. Phew! Here is the complete code for the continuation monad.</p> <pre><code>var continuationMonad = function(mv, mf) {<br /> return function(continuation) {<br /> return mv(function(value) {<br /> return mf(value)(continuation)<br /> })<br /> }<br />}<br />continuationMonad.mResult = function(value) {<br /> return function(continuation) {<br /> return continuation(value)<br /> }<br />}<br /></code></pre>Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.com2tag:blogger.com,1999:blog-7468741632426766983.post-7501342839746665372013-07-16T18:24:00.001+05:302013-07-18T18:59:16.138+05:30Functors<p>Consider the function below. </p> <pre><code>function plus1(value) { <br /> return value + 1 <br />} <br /></code></pre> <p>It is just a function that takes an integer and adds one to it. Similarly we could could have another function plus2. We will use these functions later.</p> <pre><code>function plus2(value) { <br /> return value + 2 <br />} <br /></code></pre> <p>And we could write a generalised function to use any of these functions as and when required. </p> <pre><code>function F(value, fn) { <br /> return fn(value) <br />}<br /><br />F(1, plus1) ==>> 2<br /></code></pre> <p>This function will work fine as long as the value passed is an integer. Try an array. </p> <pre><code>F([1, 2, 3], plus1) ==>> '1,2,31'<br /></code></pre> <p>Ouch. We took an array of integers, added an integer and got back a string! Not only did it do the wrong thing, we ended up with a string having started with an array. In other words our program also trashed the structure of the input. We want <code>F</code> to do the "right thing". The right thing is to "maintain structure" through out the operation.</p> <p>So what do we mean by "maintain structure"? Our function must "unwrap" the given array and get its elements. Then call the given function with every element. Then wrap the returned values in a new Array and return it. Fortunately JavaScript just has that function. Its called <code>map</code>. </p> <pre><code>[1, 2, 3].map(plus1) ==>> [2, 3, 4]<br /></code></pre> <p>And <code>map</code> is a <code>functor</code>!</p> <p>A <code>functor</code> is a function, given a value and a function, does the right thing.</p> <p>To be more specific. <br /><em>A <code>functor</code> is a function, given a value and a function, unwraps the values to get to its inner value(s), calls the given function with the inner value(s), wraps the returned values in a new structure, and returns the new structure.</em></p> <p>Thing to note here is that depending on the "Type" of the value, the unwrapping may lead to a value or a set of values.</p> <p>Also the returned structure need not be of the same type as the original value. In the case of <code>map</code> both the value and the returned value have the same structure (Array). The returned structure can be any type as long as you can get to the individual elements. So if you had a function that takes and <code>Array</code> and returns value of type <code>Object</code> with all the array indexes as keys, and corresponding values, that will also be a functor.</p> <p>In the case of JavaScript, <code>filter</code> is a <code>functor</code> because it returns an <code>Array</code>, however <code>forEach</code> is not a <code>functor</code> because it returns <code>undefined</code>. ie. <code>forEach</code> does not maintain structure.</p> <p>Functors come from category theory in mathematics, where functors are defined as "homomorphisms between categories". Let's draw some meaning out of those words.</p> <ul><li>homo = same </li><li>morphisms = functions that maintain structure </li><li>category = type</li></ul> <p>According to the theory, <code>function F</code> is a <code>functor</code> when for two composable ordinary functions <code>f</code> and <code>g</code></p> <pre><code>F(f . g) = F(f) . F(g)<br /></code></pre> <p>where <code>.</code> indicates composition. ie. functors must preserve composition.</p> <p>So given this equation we can prove wether a given <code>function</code> is indeed a <code>functor</code> or not.</p> <h2>Array Functor</h2> <p>We saw that <code>map</code> is a functor that acts on type <code>Array</code>. Let us prove that the JavaScript <code>Array.map</code> function is a <code>functor</code>.</p> <pre><code>function compose(f, g) {<br /> return function(x) {return f(g(x))}<br />}<br /></code></pre> <p>Composing functions is about calling a set of functions, by calling the next function, with results of the previous function. Note that our <code>compose</code> function above works from right to left. <code>g</code> is called first then <code>f</code>.</p> <pre><code>[1, 2, 3].map(compose(plus1, plus2)) ==>> [ 4, 5, 6 ]<br /><br />[1, 2, 3].map(plus2).map(plus1) ==>> [ 4, 5, 6 ]<br /></code></pre> <p>Yes! <code>map</code> is indeed a <code>functor</code>.</p> <p>Lets try some functors. You can write functors for values of any type, as long as you can unwrap the value and return a structure.</p> <h2>String Functor</h2> <p>So can we write a functor for type string? Can you unwrap a string? Actually you can, if you think of a string as an array of chars. So it is really about how you look at the value. We also know that chars have char codes which are integers. So we run plus1 on every char charcode, wrap them back to a string and return it. </p> <pre><code>function stringFunctor(value, fn) { <br /> var chars = value.split("") <br /> return chars.map(function(char) { <br /> return String.fromCharCode(fn(char.charCodeAt(0))) <br /> }).join("") <br />}<br /><br />stringFunctor("ABCD", plus1) ==>> "BCDE" <br /></code></pre> <p>You can begin to see how awesome <code>functors</code> are. You can actually write a parser using the string functor as the basis.</p> <h2>Function Functor</h2> <p>In JavaScript functions are first class citizens. That means you can treat functions like any other value. So can we write a functor for value of type function? We should be able to! But how do we unwrap a function? You can unwrap a function by calling it and getting its return value. But we straight away run into a problem. To call the function we need its arguments. Remember that the functor only has the function that came in as the value. We can solve this by having the functor return a new function. This function is called with the arguments, and we will in turn call the value function with the argument, and call the original functors function with the value returned! </p> <pre><code>function functionFunctor(value, fn) { <br /> return function(initial) { <br /> return function() { <br /> return fn(value(initial)) <br /> } <br /> } <br />}<br /><br />var init = functionFunctor(function(x) {return x * x}, plus1) <br />var final = init(2) <br />final() ==> 5<br /></code></pre> <p>Our function functor really does nothing much, to say the least. But there a couple things of note here. Nothing happens until you call final. Every thing is in a state of suspended animation until you call final. The function functor forms the basis for more awesome functional stuff like maintaining state, continuation calling and even promises. You can write your own function functors to do these things!</p> <h2>MayBe Functor</h2> <pre><code>function mayBe(value, fn) {<br /> return value === null || value === undefined ? value : fn(value)<br />}<br /></code></pre> <p>Yes, this is a valid <code>functor</code>.</p> <pre><code>mayBe(undefined, compose(plus1, plus2)) ==>> undefined<br />mayBe(mayBe(undefined, plus2), plus1) ==>> undefined<br />mayBe(1, compose(plus1, plus2)) ==>> 4<br />mayBe(mayBe(1, plus2), plus1) ==>> 4<br /></code></pre> <p>So mayBe passes our <code>functor</code> test. There is no need for unrapping or wrapping here. It just returns <code>nothing</code> for <code>nothing</code>. Maybe is useful as a short circuiting function, which you can use as a substitute for code like</p> <pre><code>if (result === null) {<br /> return null<br />} else {<br /> doSomething(result)<br />}<br /></code></pre> <h2>Identity Function</h2> <pre><code>function id(x) {<br /> return x<br />}<br /></code></pre> <p>The function above is known as the <code>identity function</code>. It is just a function that returns the value passed to it. It is called so, because it is the <code>identity</code> in composition of functions in mathematics.</p> <p>We learned earlier that functors must preserve composition. However something I did not mention then, is that functors must also preserve identity. ie.</p> <pre><code>F(value, id) = value<br /></code></pre> <p>Lets try this for <code>map</code>.</p> <pre><code>[1, 2, 3].map(id) ==>> [ 1, 2, 3 ]<br /></code></pre> <h2>Type Signature</h2> <p>The type signature of a function is the type of its argument and return value. So the type signature of our <code>plus1</code> function is</p> <pre><code>f: int -> int<br /></code></pre> <p>The type signature of the functor <code>map</code> depends on the type signature of the function argument. So if <code>map</code> is called with <code>plus1</code> then its type signature is</p> <pre><code>map: [int] -> [int]<br /></code></pre> <p>However the type signature of the given function need not be the same as above. We could have a function like</p> <pre><code>f: int -> string<br /></code></pre> <p>in which the type signature of <code>map</code> would be</p> <pre><code>map: [int] -> [string]<br /></code></pre> <p>The only restriction being that the type change does not affect the composability of the functor. So in general a functor's type signature can</p> <pre><code>F: A -> B<br /></code></pre> <p>In other words <code>map</code> can take an array of integers and return an array of strings and would still be a functor.</p> <p>Monads are a special case of Functors whos type signature is</p> <pre><code>M: A -> A<br /></code></pre> <p>More about monads in the next chapter.</p>Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.com3tag:blogger.com,1999:blog-7468741632426766983.post-62861408048186777902013-04-14T15:38:00.000+05:302013-07-25T14:30:01.807+05:30The Promise Monad in JavaScript<p>UPDATE: This post has been updated to a new post. All the code has been refactored and redone in the new post. <a href="http://functionaljavascript.blogspot.in/2013/07/monads.html">http://functionaljavascript.blogspot.in/2013/07/monads.html</a></p> <p>If you find it difficult to understand whats going on below, read the following posts.<br/><a href="http://functionaljavascript.blogspot.in/2013/03/implementing-monads-in-javascript.html">Implementing Monads in JavaScript</a><br/><a href="http://functionaljavascript.blogspot.in/2013/04/the-monad-laws-and-state-monad-in.html">The monad laws and state monad in JavaScript.</a></p> <p>We will go through an example of the promise monad in this post. The promise monad is available now in the <a href="https://github.com/santoshrajan/monadjs">monadjs</a> library. The best way is too look at an example. We will write a nodejs command line program that will copy an input file into an output file asynchronously. We can run the program like this.</p> <pre>$ node copy.js infile outfile</pre> <p>The program has to do the following. <ol><li>Check the command line for infile and verify it exists, if not print an error and halt computations.</li><li>Check if outfile is given in the command line otherwise print error and halt.</li><li>Read infile content into memory and halt if error.</li><li>Write content to outfile or print error to console.</li><li>Halting of program in case of error to be done without throwing errors.</li></ol></p> <p>Computations (1) (3) and (4) are asynchronous. (2) is synchronous because we are only checking process.argv.</p> <p>The monadic values of the promise monad are functions that take a continuation and promise to call the continuation either asynchronously or synchronously. The continuation is called with a value which is the result of the last computation. If the continuation is called with "null" the computations are halted.</p> <p>All the computations have access to the results of the previous computations via the "scope" variable. The results are stored in the variable names you give. <br/>Here is the source code of copy.js</p> <pre>var monads = require("monadjs");<br />var fs = require("fs");<br /><br />monads.doMonad(monads.promiseMonad,<br /> "infile",<br /> function(scope) {<br /> return function(continuation) {<br /> var fname = process.argv[2] || "";<br /> fs.exists(fname, function (exists) {<br /> if (exists) {<br /> continuation(fname);<br /> } else {<br /> console.log("File does not exist: " + fname);<br /> continuation(null);<br /> }<br /> });<br /> }<br /> },<br /> "outfile",<br /> function(scope) {<br /> return function(continuation) {<br /> var fname = process.argv[3];<br /> if (fname) {<br /> continuation(fname);<br /> } else {<br /> console.log("Output File Name is Required");<br /> continuation(null);<br /> }<br /> }<br /> },<br /> "contents",<br /> function(scope) {<br /> return function(continuation) {<br /> fs.readFile(scope.infile, function (err, data) {<br /> if (err) {<br /> console.log("Error reading File: " + scope.infile);<br /> continuation(null);<br /> } else {<br /> continuation(data);<br /> }<br /> });<br /> }<br /> },<br /> function(scope) {<br /> fs.writeFile(scope.outfile, scope.contents, function (err) {<br /> if (err) {<br /> console.log("Error writing File: " + scope.outfile);<br /> }<br /> });<br /> }<br />);</pre> <p>I don't think the promise monad obeys the monad laws. But it works. It works only for sequential asynchronous calls though. What is interesting is that it allows you to break the program structure into bite size pieces and call them sequentially. Notice also the promise monad is implemented purely functionally, and no timing loops used.</p> <p>However you don't have to actually use the promise monad from this library. I have refactored and simplified everything in a simple promise library you can <a href="https://github.com/santoshrajan/dopromise">find here</a>.</p>Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.com0tag:blogger.com,1999:blog-7468741632426766983.post-55688400528739554082013-04-05T15:00:00.000+05:302013-07-25T14:29:33.896+05:30The monad laws and state monad in JavaScript<p>UPDATE: This post has been updated to a new post. All the code has been refactored and redone in the new post. <a href="http://functionaljavascript.blogspot.in/2013/07/monads.html">http://functionaljavascript.blogspot.in/2013/07/monads.html</a></p> <p>In the <a href="http://functionaljavascript.blogspot.in/2013/03/implementing-monads-in-javascript.html">previous post</a> (please read the previous post before reading this post) we implemented three monads, the identity monad, maybe monad and array monad. However we did not get into the details of monads. We will do that in this post. Also we will implement the state monad. Here is an identity monad example.</p> <pre>var identityMonad = {<br /> mBind: function(mValue, mFunction) {<br /> return mFunction(mValue);<br /> },<br /> mResult: function(value) {<br /> return value;<br /> }<br />};<br /><br />var result = doMonad(identityMonad,<br /> "a", function(scope) {<br /> return 2;<br /> },<br /> "b", function(scope) {<br /> with (scope) {<br /> return a * 3;<br /> }<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return a + b;<br /> }<br /> }<br />);<br /><br />console.log(result);</pre> <p>First we define the identityMonad that we use when calling <code>doMonad</code>. Each computation in <code>doMonad</code> MUST return a monadic value. eg. the first computation returns <code>2</code> a monadic value. However what gets assigned to "a" is not the monadic value but the value. This distinction is important. However in the case of the identity monad both the monadic value and value are the same.</p> <p>The <code>mBind</code> function takes a monadic value and a monadic function as its arguments. mBind then extracts the "value" out of the "monadic value" and calls the monadic function with the value. In this case no extraction is done because both are equal for the identity monad. The monadic function takes a "value" and returns a "monadic value".</p> <p>In the next computation "a" is available as the value and not the monadic value. In the result computation both "a" and "b" are available and we return "value a + b". Since we return a value and not a monadic value in the final computation, the transformation from "value" to "monadic value" is done by the <code>mResult</code> function which takes a value and returns a monadic value. In this case it returns the argument itself because the value and monadic value are the same. So <code>mResult</code> is the identity function, and thats why it is called the identity monad.</p> <p>We will look at a case where the "value" and "monadic value" are not the same. Using the array monad we will write a map function that doubles each element of an array.</p> <pre>var arrayMonad = {<br /> mBind: function(mValue, mFunc) {<br /> var accum = [];<br /> mValue.forEach(function(elem){<br /> accum = accum.concat(mFunc(elem));<br /> });<br /> return accum;<br /> },<br /> mResult: function(value) {<br /> return [value];<br /> }<br />};<br /><br />var result = doMonad(arrayMonad,<br /> "i", function() {<br /> return [1, 2, 3];<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return i * 2;<br /> }<br /> }<br />);</pre> <p>Running the above code will print the result <code>[ 2, 4, 6 ]</code>. The first function in <code>doMonad</code> returns a monadic value which is an array. However the "value" in a monadic value of array type is the value of each element. It is mBinds job to extract each value, and call the monadic function for each value, and thats what it does exactly.</p> <p>The result function returns i * 2 which is of type integer. However all monadic functions of a given monad MUST return monadic values of the same type. It is mResults job to convert the result type from integer to array. And that is what it does exactly.</p> <p><b>The monad laws</b></p> <p>To write our own monads, our monads must obay the monad laws.</p> <pre>1) mBind(mResult(x), mFunction) is equal to mFunction(x).<br />2) mBind(mValue, mResult) is equal to mValue.<br />3) mBind(mBind(mValue, mFunction), mFunction2) is equal to<br /> mBind(mValue, function(x){return mbind(mFunction(x), mFunction2)}).</pre> <p>Now let us check to see if our array monad follows the monad laws.</p> <pre>var mBind = arrayMonad.mBind;<br />var mResult = arrayMonad.mResult;<br />var mValue = [1, 2, 3];<br />var x = 4;<br />var mFunction = function(x) {<br /> return [x * 2];<br />};<br />var mFunction2 = function(x) {<br /> return [x * 3];<br />};<br /><br />// Check first law<br />console.log(mBind(mResult(x), mFunction)); // [ 8 ]<br />console.log(mFunction(x)); // [ 8 ]<br /><br />//Check second Law<br />console.log(mBind(mValue, mResult)); // [ 1, 2, 3 ]<br />console.log(mValue); // [ 1, 2, 3 ]<br /><br />//Check third Law<br />console.log(mBind(mBind(mValue, mFunction), mFunction2)); // [ 6, 12, 18 ]<br />console.log(mBind(mValue, function(x){return mBind(mFunction(x), mFunction2)})); // [ 6, 12, 18 ]</pre> <p><b>The State Monad</b></p> <p>So far we saw monadic values of types integer and array. But monadic values can also be functions! After all JavaScript supports first class functions, that can be treated as values. The state monad is just such a monad. The monadic value is a function. However it is important to differentiate between a monadic function and a monadic value of type function.</p> <p>The monadic function in a state monad, just like all monadic functions takes a value and returns a monadic value. It so happens that this monadic value is a function.</p> <p>The monadic value in a state monad is a function that takes a state, and returns a two element array, with a value and the new state respectively. The state can be of any type. it can be a an integer, string, array object or any other valid type.</p> <p>In the next example we maintain an immutable stack array over a set of computations. We define two monadic functions "push" and "pop".</p> <pre>var stateMonad = {<br /> mBind: function(mValue, mFunc) {<br /> return function(state) {<br /> var compute = mValue(state);<br /> var value = compute[0];<br /> var newState = compute[1];<br /> return mFunc(value)(newState);<br /> };<br /> },<br /> mResult: function(value) {<br /> return function(state) {<br /> return [value, state];<br /> };<br /> }<br />};<br /><br />var push = function(value) {<br /> return function(state) {<br /> var newstate = [value];<br /> return [undefined, newstate.concat(state)];<br /> };<br />};<br /><br />var pop = function() {<br /> return function(state) {<br /> var newstate = state.slice(1);<br /> return [state[0], newstate];<br /> };<br />};<br /><br />var result = doMonad(stateMonad,<br /> "a", function(scope) {<br /> return push(5);<br /> },<br /> "b", function(scope) {<br /> with (scope) {<br /> return push(10);<br /> }<br /> },<br /> "c", function(scope) {<br /> with (scope) {<br /> return push(20);<br /> }<br /> },<br /> "d", function(scope) {<br /> with (scope) {<br /> return pop();<br /> }<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return d;<br /> }<br /> }<br />);<br /><br />console.log(result([]));</pre> <p>Running the code above will print [ 20, [ 10, 5 ] ].</p> <p>20 is the value of the last "pop" computation, and the second value is the final state of the stack.</p> <p>First we will look at <code>mResult</code>. <code>mResult</code> is a monadic function that takes a value and returns a monadic value, which is a function that takes a state and returns an array with value and state.</p> <p><code>mBind</code> returns a monadic value which is a function. So the result of <code>doMonad</code> is a function which you must call with an initial value for the stack. Which is <code>[]</code> in our case. Remember <code>mBind</code> is called with a monadic value and a monadic function. It has to extract the value out of the monadic value and call the monadic function with the value. Which it does in the three lines inside the returned monadic function. Notice that <code>mFunc</code> is called with the extracted value, and since its return value is a monadic value of type function, the function is called immediately with the new state.</p> <p>All the code in the last two posts are available as a <a href="https://github.com/santoshrajan/monadjs">monad library on github</a>.</p>Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.com0tag:blogger.com,1999:blog-7468741632426766983.post-65962314828116481502013-03-29T14:14:00.000+05:302013-07-25T14:29:11.032+05:30Implementing Monads in JavaScript<p>UPDATE: This post has been updated to a new post. All the code has been refactored and redone in the new post. <a href="http://functionaljavascript.blogspot.in/2013/07/monads.html">http://functionaljavascript.blogspot.in/2013/07/monads.html</a></p> <p></p> <p>Consider the problem of doing a series of computations (calling a series of functions), and you want each successive computation to have access to the results of the previous computations. We will write a function called <code>doComputations</code>, and here is how a call to <code>doComputations</code> would look like.</p> <pre>var result = doComputations(<br /> "a", function(scope) {<br /> return 2;<br /> },<br /> "b", function(scope) {<br /> with (scope) {<br /> return a * 3;<br /> }<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return a + b;<br /> }<br /> }<br />);</pre> <p>The arguments to <code>doComputaions</code> are one or more "string - function" pairs and the last argument is just a "result" function. The string is a variable name which will be assigned the value returned from calling the function. So in the first case "a" will be assigned the value 2. What is interesting is that "a" is visible inside the next function whose value gets assigned to "b". And both "a" and "b" are visible inside the last function. Every function is called with a "scope" object which carries key value pairs corresponding to the previous computations carried out. Here we use the "with" statement to scope the "scope" object within the function. If you don't want to use the "with" statement you could access the variable from the scope object directly eg. scope.a, scope.b. The value returned by doComputations is the value returned by the last "result" function, in this case the final value is 8. And here is the definition of <CODE>doComputations</CODE>.</p> <pre>function doComputations() {<br /> var args = arguments;<br /> var scope = {};<br /> function iterator(i) {<br /> if (args.length === i + 1) {return args[i](scope);}<br /> var varName = args[i];<br /> var func = args[i + 1];<br /> var value = func(scope);<br /> scope[varName] = value;<br /> return iterator(i + 2);<br /> }<br /> return iterator(0);<br />}</pre> <p>Inside <code>doComputations</code> we define an iterator function, which recursively iterates over the arguments array of <code>doComputations</code>. In the first line of the iterator function we check to see if we have reached the last "result function", if yes we call it with <code>scope</code> and return the result. In the next three lines we create three variables initialised to the variable name, function, and value returned by calling the function with the <code>scope</code>. In the next line we attach the key-value to <code>scope</code>. And finally we make a recursive call to the iterator to do the next computation. In the last line of <code>doComputations</code> we start the iterator with initial values 0 for the index.</p> Copy the two code fragments above into a file, add the a final line: <pre>console.log(result);</pre>and run it. You should get the result as 8. <p>All this looks like lots of work just to add and multiply a couple of integers, but we have done something useful. For one we have abstracted away the nitty gritty of iterating over computations, with visibility of previous results, into a function called <code>doComputations</code>.</p> Computations are not always so simple and straight forward as the one above. What if we wanted to abort the computations midway for some reason? eg. If any of the functions returns "null" we want to abort the computations. There are many other types of computations and to write a version of <code>doComputations</code> for each type is not a good idea. Instead we could make <code>doComputations</code> call another function between computations so that any thing different, we want to do, is done in this function. This function is passed to <code>doComputations</code> as its first argument. We will call this function "mBind". Now all we have to do is write a version of <code>mBind</code> for every type of computation. For every computation, <code>doComputations</code> will call <code>mBind</code> which in turn will call the next computation. First we write the <code>mBind</code> function to handle null values returned by any computation. <pre>var mBind = function(mValue, mFunction) {<br /> if (mValue === null)<br /> return null;<br /> else<br /> return mFunction(i + 2);<br />}</pre> <p>Now the iterator function will call mBind, which is passed as an argument to doComputations, which in turn will recursively call the iterator.</p> <pre>function doComputations(mBind) {<br /> var args = arguments;<br /> var scope = {};<br /> function iterator(i) {<br /> if (args.length === i + 1) {return args[i](scope);}<br /> var varName = args[i];<br /> var func = args[i + 1];<br /> var value = func(scope);<br /> return mBind(value, function() {<br /> scope[varName] = value;<br /> return iterator(i + 2);<br /> });<br /> }<br /> return iterator(1);<br />}</pre> <p>Below we call <code>doComputations</code> whose first argument is the <code>mBind</code> function. Also we want to abort the computations in case the browser does not support the <code>console.log</code> function. <pre>var result = doComputations(mBind,<br /> "a", function(scope) {<br /> if (typeof console === "object" && console.log)<br /> return 2;<br /> else<br /> return null;<br /> },<br /> "b", function(scope) {<br /> with (scope) {<br /> return a * 3;<br /> }<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return a + b;<br /> }<br /> }<br />);</pre> <p>We can now use doComputations for various types of computations by simply changing the <code>mBind</code> function passed to it. It would be even better if we could predefine the <code>mBind</code> function for various types of computations. And that is what we will do below. We will also change the name of <code>doComputations</code> to <code>doMonad</code>. And we will add <code>mBind</code> as the property of an object called "monad".</p> <pre>var maybeMonad = {<br /> mBind: function(mValue, mFunction) {<br /> if (mValue === null)<br /> return null;<br /> else<br /> return mFunction(mValue);<br /> }<br />};<br /><br />function doMonad(monad) {<br /> var args = arguments;<br /> var scope = {};<br /> function iterator(i) {<br /> if (args.length === i + 1) {return args[i](scope);}<br /> var varName = args[i];<br /> var func = args[i + 1];<br /> var value = func(scope);<br /> return monad.mBind(value, function() {<br /> scope[varName] = value;<br /> return iterator(i + 2);<br /> });<br /> }<br /> return iterator(1);<br />}</pre> <p>Compare the above code to the previous listing. It is pretty much the same, except that we have renamed <code>doComputations</code>, and the <code>mBind</code> function is now passed as the property of an object, and this object is called a monad, and in this specific case we called the monad the "maybeMonad". Because "maybe" the computations are carried out, or "maybe" they won't be.</p> <p>A monad MUST have two properties defined for it to be a proper monad. "mBind" and "mResult". We have not seen <code>mResult</code> so far. <code>mResult</code> is a wrapper function for the "result" function. So we add support for <code>mResult</code> in <code>doMonad</code> below. Also we define a new monad called the <code>arrayMonad</code> below and we do some computations with the it.</p> <pre>function doMonad(monad) {<br /> var args = arguments, scope = {};<br /> function iterator(i) {<br /> if (args.length === i + 1) {<br /> return monad.mResult(args[i](scope));<br /> }<br /> var varName = args[i];<br /> var func = args[i + 1];<br /> var value = func(scope);<br /> return monad.mBind(value, function(value) {<br /> scope[varName] = value;<br /> return iterator(i + 2);<br /> });<br /> }<br /> return iterator(1);<br />}<br /><br />var arrayMonad = {<br /> mBind: function(mValue, mFunc) {<br /> var accum = [];<br /> mValue.forEach(function(elem){<br /> accum = accum.concat(mFunc(elem));<br /> });<br /> return accum;<br /> },<br /> mResult: function(value) {<br /> return [value];<br /> }<br />}<br /><br />var result = doMonad(arrayMonad,<br /> "a", function() {<br /> return [1, 2];<br /> },<br /> "b", function() {<br /> return [3, 4];<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return a + b;<br /> }<br /> }<br />);<br /><br />console.log(result);<br /></pre> <p>Running the code above will yield a result of [ 4, 5, 5, 6 ]. The computations using the arrayMonad each return an array. The final result function is called with values a and b, for each element of both arrays. ie it will be called with (1,3), (1,4), (2,3), (2,4). And the addition of each of the elements yields the returned array of [ 4, 5, 5, 6 ].</p> <p>Using the <code>arrayMonad</code> let us implement a two dimensional iterator function in JavaScript called <code>forEach2D</code>. It will take 3 arguments, an <code>iArray</code>, a <code>jArray</code>, and a <code>callback</code>. The callback is called for each value of i and j. Here is the code below.</p> <pre>function forEach2D(iArray, jArray, callback) {<br /> return doMonad(arrayMonad,<br /> "i", function() {<br /> return iArray;<br /> },<br /> "j", function() {<br /> return jArray;<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return callback(i, j);<br /> }<br /> }<br /> );<br />}<br /><br />var result = forEach2D([1, 2, 3], [4, 5, 6], function(i, j) {<br /> return [i, j];<br />});<br /><br />console.log(result);<br /></pre> Running the code above will yield result: <pre>[ [1, 4],[1, 5],[1, 6],[2, 4],[2, 5],[2, 6],[3, 4],[3, 5],[3, 6] ]</pre> <p>How about a function for iterating over three arrays? A forEach3D function. Easy!</p> <pre>function forEach3D(iArray, jArray, kArray, callback) {<br /> return doMonad(arrayMonad,<br /> "i", function() {<br /> return iArray;<br /> },<br /> "j", function() {<br /> return jArray;<br /> },<br /> "k", function() {<br /> return kArray;<br /> },<br /> function(scope) {<br /> with(scope) {<br /> return callback(i, j, k);<br /> }<br /> }<br /> );<br />}<br /><br />var result = forEach3D([1, 2], [3, 4], [5, 6], function(i, j, k) {<br /> return [i, j, k];<br />});<br /><br />console.log(result);</pre> And running this code will print out: <pre>[ [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6] ]</pre> <p>You can begin to see the power of monads here. They abstract away the complicated part of your code and simplify the problem at hand. Monads are a hard concept to understand, and I hope that I have simplified its understanding here. If there is any part not clear enough please let me know. In <a href="http://functionaljavascript.blogspot.in/2013/04/the-monad-laws-and-state-monad-in.html">the next post</a> I hope to take a more in depth look and monads with some interesting examples.</p> Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.com0tag:blogger.com,1999:blog-7468741632426766983.post-42527234849925134052013-03-27T14:17:00.000+05:302013-03-27T14:17:32.128+05:30Introduction to Functional JavaScript<p>JavaScript was a functional programming language even before it got its name! Back in 1995 Netscape Communications the makers of the Netscape Browser realized that their browser needed a scripting language embedded in HTML. They hired Brendan Eich to embed the Scheme programming language in HTML. Scheme was a full fledged functional programming language. To his dismay “the powers that be” encouraged Brendan to come up with a more traditional programming language. His first cut was a language called “Mocha” in May 1995, and it retained that name till December 1995. It was first renamed “LiveScript” and soon after that Netscape and Sun did a license agreement and it was called “JavaScript”. But by then Brendan Eich had sneaked in some “functional programming” features into JavaScript.</p> <p>The story gets more complicated, and we will delve into it. Because this story will tell you why JavaScript is what it is today. Brendan Eich claims that hiring him to embed the Scheme language, might actually have been a “bait and switch operation”. But at that point in time Netscape was also negotiating with Sun to embed Java in the browser. Note that JavaScript was for embedding in HTML while Java was for embedding in the Browser. The idea was that Java would be used for component development while JavaScript would be used for lightweight scripting within HTML.</p> <p>We don't know what actually transpired, but the orders from above to Brendan where clear. The new scripting language must “look like Java” and must be “object based”. Any hopes Brendan might have harboured for Scheme, where now out of the window. We will see why.</p> <b>Programming Paradigms</b><p>We can only speculate on what “look like Java” meant. However we can be certain that it had to be a “curly brace” language. Curly brace languages define statement blocks using curly braces, the “{“ and “}” characters. Indeed Java syntax was fashioned on another curly brace language “C++”, which in turn was fashioned on “C”. Here is how a for-loop looks in Java.</p> <pre>for (int i = 0; i < 10; i++) {<br /> System.out.println("Hello");<br /> System.out.println("World");<br />}</pre> The same for-loop in C. <pre>int i;<br />for (i = 0; i < 10; i++) {<br /> printf("Hello\n");<br /> printf("World\n");<br />}</pre> And the for-loop in JavaScript. <pre>for (var i = 0; i < 10; i++) {<br /> console.log("Hello");<br /> console.log("World");<br />}</pre> <p>Indeed JavaScript does look like Java. And C too. However curly braces where not the only implications for a language to “look like Java”. Java is an imperative/object oriented style programming language. JavaScript also had to be an imperative/object oriented style language.</p> <p>Programming languages are made up of operators, conditional statements, loop statements and functions. Having conditional statements and loop statements are hallmarks of an “imperative” style programming language. Functional style languages tend to support operators and functions only.</p> <p>It is interesting that none of the three languages, Java, C++ and C, were functional programming languages. While C was an imperative programming language, C++ and Java were Imperative/Objected Oriented programming languages. By now you would have guessed that the three programming paradigms (styles) were imperative, object oriented and functional. There is one more, the declarative paradigm.</p> <p>The differences between these paradigms are because of the foundations on which they were based. Imperative and object oriented programming are based on the “turing machine”. Functional programming is based on “lambda calculus” and declarative programming is based on “first order logic”. In this post we will look at the differences between, imperative, object oriented and functional programming at a more practical level.</p> <p>An imperative programming language is one in which program state change is achieved by executing a series of statements, and does flow control primarily using conditional statements, loop statements and function calls. The program given below is a simple implementation of the JavaScript <code>Array.join</code> method in an imperative manner.</p> <pre>function simpleJoin(stringArray) {<br /> var accumulator = '';<br /> for (var i=0, l=stringArray.length; i < l; i++) {<br /> accumulator = accumulator + stringArray[i];<br /> }<br /> return accumulator;<br />}</pre> <p>The code above is straight forward. We iterate through an array and add each string element to the accumulator and return the accumulator. We will now rewrite this function in an object oriented manner. Since JavaScript has an Array class, we will add this method to the Array class, so that every instance of this class has access to this function. JavaScript use prototypal inheritance and so we add this function to the Array prototype.</p> <pre>Array.prototype.simpleJoin = function() {<br /> var accumulator = "";<br /> for (var i=0, l=this.length; i < l; i++) {<br /> accumulator = accumulator + this[i];<br /> }<br /> return accumulator;<br />}</pre> <p>As we can see, the object oriented version is quite like the imperative version, except that the function (method) is now a method of the class. Object oriented languages tend to be imperative languages also.</p> Now let us write the functional version of this function. <pre>function simpleJoin(stringArray, i, accumulator) {<br /> if (i === stringArray.length) {<br /> return accumulator;<br /> } else {<br /> return simpleJoin(stringArray, i+1, accumulator+stringArray[i])<br /> }<br />}</pre> <p>The first thing to note is that we are not using the for loop here for iteration. Instead we use recursion for iteration. Recursion happens when the function calls itself from within itself. Indeed this is one of the characteristics of a functional programming language. eg. Scheme does not have any loop statements. Instead it uses recursion for iteration. The function is called for the first time with the given array in stringArray, <code>i</code> set to <code>0</code>, and accumulator set to <code>""</code>. The second time around the function is called from within itself with the same <code>stringArray</code>, <code>i</code> set to <code>i + 1</code>, and <code>accumulator</code> set to <code>accumulator + stringArray[i]</code>. And we continue the same way until <code>i === stringArray.length</code> when we return the <code>accumulator</code>. We will discuss recursion in detail later in a later post. Just remember we used recursion for doing iteration here.</p> <p>There is still something imperative about this function. The <code>if</code> statement. Functional languages tend to use expressions that evaluate to some value, instead of statements that don't evaluate to anything. So let us rewrite the function, to make it as functional as possible in JavaScript.</p> <pre>function simpleJoin(stringArray, i, accumulator) {<br /> return (i === stringArray.length) ? accumulator :<br /> simpleJoin(stringArray, i + 1, accumulator + stringArray[i])<br />}</pre> <p>Now this as functional as you can get with JavaScript. Instead of the <code>if</code> statement we return the value evaluated by the conditional operator <code>?</code>. The conditional operator <code>?</code> Takes a conditional expression and returns the value of one of the two expressions based the condition being true or false. The value of the first expression is returned if <code>true</code> and the second if <code>false</code>.</p> <p>We can see that the functional version is concise. Indeed one of the advantages of functional programming is that it lends itself to lesser code to accomplish the same thing, leading to better readability and maintainability.</p> <p>However in the case of JavaScript, as of now you cannot use recursion for doing iteration. You should continue to use the imperative or object oriented method for iteration. This is because JavaScript does not (yet) support “tail call optimization”. For doing proper recursion, tail call optimization is required. We will discuss tail recursion, and tail call optimization, and how to get around this problem in a future post. As of writing this post tail call optimization is expected in ecmascript 6.<p> <p>So is JavaScript an imperative language, or an object oriented language, or a functional language? It is a multi paradigm language. It does not have all the functional features implemented. But it is slowly getting there. This is also true of most other languages. Most languages (other than functional languages to begin with) have added functional features to various degrees over the years. A good example of the multi paradigm nature of JavaScript is the <code>Array.forEach</code> method. Here is a possible simple implementation. Note that all modern browsers have already implemented this.</p> <pre>Array.prototype.forEach = function(callback) {<br /> for (var i = 0, len = this.length; i < len; ++i) {<br /> callback(this[i], i, this);<br /> }<br />}</pre> <p>In the code above the for-loop part of the code is imperative. Adding to the array prototype and usage of <code>this</code> is object oriented. Passing a function as an argument to another function (callback) is functional and is a feature of functional programming known as “higher order function”. In JavaScript, we take this for granted, passing functions as an argument. Surprisingly this was not a feature found in the most popular languages until recently. eg. You cannot pass functions as arguments in Java, though you can do it indirectly via Interfaces. Same is the case with C, though you can do it indirectly using pointers.</p> <b>Programming Abstractions</b><p>What if JavaScript did not have the “passing functions as arguments feature”? The answer to this question is crucial to understanding what functional programming brings to the table. For one, we would not be able to write the <code>Array.forEach</code> function above. And even worse, every time we had to iterate over an array, we would have to write the same for-loop again and again. If we had <code>Array.foreach</code> we need to think only about writing the callback. We need to think only of what to do with each element of the array, and need not concern ourselves with iterating over the array. In other words we have “abstracted” away the iteration part of the problem, and freed ourselves to concentrate on each element of the array.</p> <p>Abstractions are about hiding away implementation details, thereby reducing and factoring out details, so that programmers can focus on the problem at a higher level. Abstractions can be code abstractions, as we saw in the example above, and data abstractions. Objected oriented programming is about combining code and data abstractions into one abstraction called the class. In functional programming we use functional features like first class functions, nested functions, anonymous functions and closures to abstract away code and sometimes even data. Monads are an esoteric feature of functional programming that can even abstract away program structure!</p> <p>Macro's are another feature that allows code abstraction. However macros are not a feature of functional programming. But they are found in all Lisp like functional languages like Lisp, Scheme, Clojure etc. There are attempts to bring Macro's to JavaScript and at the moment it is very much early days.</p> <p>A good example of the power of functional abstractions is jQuery. jQuery is the mother of all functional abstractions. It has abstracted away the JavaScript language itself! So much so that you wouldn't be surprised, if you found a jQuery programmer who knows very little or no JavaScript. As of Feb 2013 there was one publisher who had 32 jQuery books listed, and not a single JavaScript book! And jQuery has achieved so much mostly using only two functional features, functions as arguments and closures.</p> <b>First Class Functions and Closures</b><p>The functional programming feature that Brendan Eich implemented in JavaScript was “first class functions”. Functions are first class if they are treated as “first class citizens” of that language. Which implies functions are treated just like all other variables. ie. You can pass them as arguments to functions, you can return them as values from other functions, or you can assign them to variables or data structures. We have seen “passing functions are arguments” earlier. Here is an example of assigning a function to a variable.</p> <pre>function greet(name) {<br /> console.log("Hello " + name);<br />}<br /><br />greet("John"); // "Hello John"<br /><br />var sayHello = greet;<br />sayHello("Alex"); // "Hello Alex"</pre> <p>Some programming language theorists consider “anonymous functions” as first class functions. Not to be outdone, Brendan Eich threw anonymous functions into the mix. This is like letting the cat among the pigeons so to speak. But not for Brendan Eich, he knew the solution to the problem. Here is an anonymous function in JavaScript.</p> <pre>function(name) {<br /> console.log(“Hello “ + name);<br />}</pre> <p>If you noticed we did not give this function a name. After all, it is an anonymous function. If you try to run the code above, you will get an error. Something to the effect “you cannot run the code in this context”. And rightly so. They can only be assigned to something, or passed as arguments to a function.</p> <pre>var sayHello = function(name) {<br /> console.log(“Hello “ + name);<br />}<br />sayHello("Jane"); // "Hello Jane"</pre> <p>What if we wanted to change the greeting? Sometimes we would like to say “Hi” instead of “Hello”. We could create a generic “createGreeting” function, which would in turn “compose” another function for you, and return the new composed function. So if we wanted to sat “Hi” it would return a function, and if we wanted to say “Hello” it would return another function that says “Hello”. We can do all that because JavaScript supports first class functions, and we can return functions from other functions. Here is the code.</p> <pre>function createGreeting(greeting) {<br /> return function(name) {<br /> console.log(greeting + " " + name);<br /> }<br />}<br />var sayHi = createGreeting("Hi");<br />sayHi("Jack"); // "Hi Jack"<br />var sayHello = createGreeting("Hello");<br />sayHello("Jack"); // "Hello Jack"</pre> <p>The <code>createGreeting</code> function takes a greeting as its argument. The function returns a newly created anonymous function. However the newly created anonymous function was created inside another function <code>createGreeting</code>. So it is also a nested function now. Now since our language supports anonymous functions it will also have to support nested functions. And when we return nested functions from our function we run into another problem. We will look at that in more detail.</p> <p>The anonymous function takes a name argument and prints to the console <code>greeting + name</code>. The variable name is an argument to the anonymous function, and behaves just like any other variable defined within the function. In other words <code>name</code> is “local” to the anonymous function. But this is not true of the variable <code>greeting</code>. It is defined in another function called <code>createGreeting</code> and hence is “non local” to the anonymous function. However the anonymous function can access the variable greeting due to something called lexical scoping.</p> <p>The “scope” of a variable is its “visibility” within a program. “Lexical scope” means that visibility is limited to all the text (code). So when we say “local variables are lexically scoped” within a function, it means that the function's local variables are visible to all the text (code) in the function, even if the code is within another nested function. This also means that when you run the nested function outside the lexically scoped environment, the nested functions non local variable will not be visible. And there lies the problem of returning nested functions from another function. And indeed thats what we are doing here.</p> <pre>var sayHi = createGreeting("Hi");</pre> <p>In the line above we assign the returned anonymous function to variable sayHi. And call the function in the next line.</p> <pre>sayHi(“Jack”)</pre> <p>We are calling <code>sayHi</code> outside of <code>createGreeting</code>. And the <code>greeting</code> variable is not available outside of <code>createGreeting</code>. The variables it may access in the scope where it was defined, may not be available in the scope where it was actually called. Thats why languages like C don't support nested functions. For this to work the language needs to support another functional programming feature called “closures”. JavaScript supports closures. As matter of fact it has to support closures. Any language that supports first class functions and nested functions has to support closures.</p> <p>A function's closure is a reference to all its non local variables. In the previous example <code>greeting</code> was the non local variable and <code>name</code> was the local variable. A closure is a table of references to all of a functions non local variables. This allows the function to continue to refer to the non local variable even when the function is out of the scope of the variables.</p>Santosh Rajanhttp://www.blogger.com/profile/04123305937973885088noreply@blogger.com1