mostly-adequate-guide icon indicating copy to clipboard operation
mostly-adequate-guide copied to clipboard

Question on Chapter 10: "ap will never change container types"

Open thurt opened this issue 9 years ago • 5 comments

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))

thurt avatar Apr 26 '16 04:04 thurt

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))

thurt avatar Apr 26 '16 17:04 thurt

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.

safareli avatar Apr 27 '16 09:04 safareli

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?

thurt avatar Apr 27 '16 17:04 thurt

That looks good to me

safareli avatar Apr 28 '16 09:04 safareli

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.

KtorZ avatar Jan 21 '18 12:01 KtorZ