It turns out we already have one functor: map()
. It grabs the values within the container, an array, and applies a function to it.
[1, 4, 9].map(Math.sqrt); // Returns: [1, 2, 3]
However, we'll need to write it as a global function and not as a method of the array object. This will allow us to write cleaner, safer code later on.
// map :: (a -> b) -> [a] -> [b] var map = function(f, a) { return arr(a).map(func(f)); }
This example seems like a contrived wrapper because we're just piggybacking onto the map()
function. But it serves a purpose. It provides a template for maps of other types.
// strmap :: (str -> str) -> str -> str var strmap = function(f, s) { return str(s).split('').map(func(f)).join(''); } // MyObject#map :: (myValue -> a) -> a MyObject.prototype.map(f{ return func(f)(this.myValue); }