In Haskell you can apply fmap
to two functions, which is basically function composition. You can even compose fmap
to enable function composition of functions with higher arity (fmap . fmap
).
This works because functions are functors.
How would such a functor (or the appropriate map
method) be implemented in Javascript?
This is what I have tried so far:
funcProto = {
map(f) { return y => f(this.x(y)) }
};
function func(x) {
return Object.assign(Object.create(funcProto), {x: x});
}
const comp = f => g => x => f(g(x));
const map = f => ftor => ftor.map(f);
const sub = y => x => x - y;
const sqr = x => x * x;
const inc = x => x + 1;
This works for normal function composition:
func(sqr).map(inc)(2); // 5
However, it doesn't work for a composed version of map
:
const map2 = comp(map)(map);
map2(sub)(sub)(10)(5)(4); // Error
I think I adapt myself too much to the traditional way functors are implemented in Javascript. Functions as functors behave differently from list or maybe.