Inception (aka Currying)

I came across this awesome technique using partial evaluation called currying while trying to re-implement memoize in underscoreJS. I think of it as the inception* of coding.

I think currying is best explained through code.

Let's say you have a function greet that takes in a parameter of x and returns an anonymous function that takes a parameter of y.

var greet = function(x){
	return function(y){
    	var result = x.concat(" ").concat(y);
        return result;
    }
};

How curious, you say to yourself. If you invoke greet with an argument of "hi", that gets assigned to x...but what about that y in the anonymous function that's returned.

THIS IS INCEPTION, ladies and gentlemen!! Here is the curry action.

Our greet function is the curried function.
How do we use it?

Let's set it to a variable and pass in "hi".

var name = greet("hi");

This essentially "prefills" our greet function with "hi". In order to invoke greet, we need to invoke our name function.

name("ben"); //--> "hi ben"
name("jerry"); //--> "hi jerry"

WHOA, right?! Our anonymous function in greet pulls out the argument that's in the function that's invoking greet!

Now that we have this curry superpower, let's check out memoize.

Memoize stores a given function's results. When the function is called, memoize will check to see if it has already computed the result for the given argument and returns that value if possible.

Here's my re-implemented version of memoize:

var memoize = function(func){
	var storage = {};
	return function(arg){
		if(!storage[arg]){
			storage[arg] = func.call(null,arg);
		}
		return storage[arg];
	}
}

To use it, let's first create a function to pass through memoize as an argument (add). Then we can create a variable func set to memoize with add as an argument.

var add = function(x){
	return x+x;
}
var func = memoize(add);
func(5); //--> 10
func(10); //--> 20

Memoize will only run add if it has not yet been run for the given argument. The results are stored in the variable storage found in memoize.

Trippy stuff! I hope I explained it well.

A useful source I found was this.

*I have actually never seen Inception. Here it just means something's in something that's in something and crazy things happen.