Just for fun I decided to put together a quick sample of some functional JavaScript – as in, functional programming done with JavaScript. I’m not really very familiar with functional languages other than playing with Haskell a bit and doing some functional-style stuff in C# and Ruby. I wanted to see what a functional JavaScript code base might look like.

## A Functional Calculator

To keep things simple, I created a calculator using nothing but functions. Each function takes other functions as parameters and returns a function. The only exception to this is the simple `value` function which takes a value and returns a function that itself will return the original value.

Here’s the basic code I wrote for my calculator, including the aforementioned `value` function:

```
// A raw value, represented as a function
var value = function(val){
return function(){
return val;
}
}
// A function to add two functions together
var add = function(x, y){
return function(){
return x() + y();
}
}
// A function to subtract one function from another
var subtract = function(x, y){
return function(){
return x() - y();
}
}
// A function to multiply two functions
var multiply = function(x, y){
return function(){
return x() * y();
}
}
```

I wrote all this through the use of some Jasmine tests, but as a quick example of how it can work, here’s a simple formula and result:

```
var one = value(1);
var two = value(2);
var three = value(3);
var four = value(4);
// (1 + 2) * 3 - 4 == 5
var resultFunc = subtract(multiply(add(one, two), three), four);
// but it's still a function right now, so evaluate it
var result = resultFunc();
consol.log(result); // => 5
```

## My Thoughts And Reactions

These are the interesting points that stand out in my head. I’m not sure if these are “correct” or not… it’s just what pops out in my mind.

If anyone has any corrections and additional thoughts or notes, I’d love to hear them – just drop me a line in the comments, below.

#### Functions And Functions As State

I’ve represented everything as a function – even the simple values of 1 through 4. And every function returns a function, except for the simple values, which return a function that returns the actual value.

In the process of returning functions from functions, I’m representing the state of the application as a series of functions.

This one is a bit odd for me to wrap my head around. I’m not sure if this is really correct, or if it’s just an oversimplification of what’s really happening here. There are no data-structures, though, only functions. So it stands to reason that the state is stored as a series of functions that can be evaluated to produce a result.

**Update**: The Wikipedia article on functional programming says that fp “avoids state”. So… am I wrong in thinking that I’ve represented the state with functions instead of data structures?

#### Funcional Command Pattern

The result isn’t actually evaluated until I invoke the`resultFunc` in the above example. But I have the `resultFunc`available as a variable and I can pass it around anywhere I want. This basically turns it into a command pattern implementation, only in a functional manner instead of an object manner.

#### Compose-able And DSL Functions

All of these functions are side effect free. None of them actually mutates any existing application state. Of course this is a really simple implementation, but that was one of my goals. I’ll need to play with some more complex ideas in order to really see how side effect free would play out.

One of the benefits of side effect free functions is that the code in the sample is far more declarative and compose-able than most code I write. Since each function does one very small and very simple thing, taking in other functions as parameters, it’s easy to build things.

```
var one = value(1);
var two = value(2);
var three = value(3);
var four = value(4);
// (1 + 2) * 3 - 4 == 5
var added = add(one, two)
var multiplied = multiply(added, three)
var resultFunc = subtract(multiplied, four);
// the result is the same.
// it's been composed the same, functionally
// it was just put together with more variables in the mix
var result = resultFunc();
consol.log(result); // => 5
```

This is something that I’ve played with in other languages, and I like this aspect of functional programming. It’s a great way to build DSLs for example.

#### Compared To Object / Prototypal

Oscar Godson posted a version of my code alongside a prototypal version for a comparison.

```
/**
Prototypal
from Oscar Godson: http://jsbin.com/atopek/edit#javascript
*/
var Calc = function(){
this.sum = 0; //could be a param
return this;
}
Calc.prototype.add = function(x){
this.sum = this.sum + x;
return this;
}
Calc.prototype.multiply = function(x){
this.sum = this.sum * x
return this;
}
Calc.prototype.subtract = function(x){
this.sum = this.sum - x;
return this
}
Calc.prototype.result = function(){
return this.sum;
}
console.log(new Calc().add(1).add(2).multiply(3).subtract(4).result())
```

I like seeing them side by side. It’s interesting the see all of the different ways that JavaScript can do the same thing. It also shows me just how ugly I think the functional version is. When you compare the actual formula in the comments to the functional JS code, the code is inside-out-backwards. The prototypal code with it’s method chaining is closer to the formula, though it’s still a bit off.

I think it’s easier to read and understand the chaining, though. It also reminds me of LINQ and monads – pipes and filters with a single result coming from the end of it.

#### More Fun Functional Stuff To Try

I haven’t done anything like memoizing or currying for these simple examples, but those are ideas I want to play with, too. I’ve written a currying function in JavaScript once or twice, and there’s plenty of examples in the good JS books. Memoizing is also available in Underscore.js but should be trivial to implement a naive version of it. I’m sure there are plenty of other things that would be fun to try, as well.

Code And Continuing Thoughts (Maybe)

If you’re interested in seeing this code, it’s on Github.

I’m thinking about taking this a little further over time, just for fun. I’ve posted these comments in the read me (actually – they started there…) and I’ll continue to update the read me as I progress (assuming I actually do continue exploring this and don’t just forget about it like so many other things).

This is really pretty simple stuff… but it’s fun to write asimple exercise like this and think about what’s going on, why and see how it affects the way I think and approach software development.