Книга: Functional Programming in JavaScript
Назад: Creating functors
Дальше: Function compositions, revisited

Arrays and functors

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 . 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 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
Назад: Creating functors
Дальше: Function compositions, revisited

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)