Question on Chapter 10: "ap will never change container types"
you should know that applicatives are "closed under composition", meaning ap will never change container types on us(yet another reason to favor over monads)
Container.prototype.ap = function(other_container) {
return other_container.map(this.__value);
}
According to the provided definition of ap, it appears that you could change the container type because there is no enforced type checking on the two container instances. I see the same issue with the liftA2 function.
Wouldn't this example change the initial Container type to the Maybe type?:
Container.of(x => { return x }).ap(Maybe.of(2))
Or consider liftA2:
var liftA2 = function(f, functor1, functor2) {
return functor1.map(f).ap(functor2)
}
// -- the .ap in liftA2 changes the type from Container to Maybe
liftA2(add, Container.of(2), Maybe.of(3))
If you look at definition of ap from here (<*>) :: f (a -> b) -> f a -> f b it shows that all functors should be of same type.
So yes type will change as we are not type checking it in js, but I think you should not do that.
Thanks @safareli -- this is what I suspected.
I think there should be more explanation in the book on this topic of type checking. I would add something like this:
"In JS, you must make sure that you are using the same functor type on both sides of ap. Otherwise, you will be using ap in a way that is inconsistent with its definition in other FP languages."
What do you think?
That looks good to me
Agreed that this deserve a paragraph in the book somewhere in the introduction or preface. A lot of functions and data structures presented actually holds under the assumption that they're used in the way they're expected to be used.
Will do.