Arrays are the preferred way to work with data in functional JavaScript.
Is there an easier way to create functors that are already assigned to a morphism? Yes, and it's called arrayOf
. When you pass in a morphism that expects an integer and returns an array, you get back a morphism that expects an array of integers and returns an array of arrays.
It is not a functor itself, but it allows us to create functors from morphisms.
// arrayOf :: (a -> b) -> ([a] -> [b]) var arrayOf = function(f) { return function(a) { return map(func(f), arr(a)); } }
Here's how to create functors by using morphism:
var plusplusall = arrayOf(plusplus); // plusplus is our morphism console.log( plusplusall([1,2,3]) ); // returns [2,3,4] console.log( plusplusall([1,'2',3]) ); // error is thrown
The interesting property of the arrayOf
functor is that it works on type safeties as well. When you pass in the type safety function for strings, you get back a type safety function for an array of strings. The type safeties are treated like the identity function morphism. This can be very useful for ensuring that an array contains all the correct types.
var strs = arrayOf(str); console.log( strs(['a','b','c']) ); // returns ['a','b','c'] console.log( strs(['a',2,'c']) ); // throws error