Is the implementation of `<*>` based on `fmap` special to Maybe applicative or can it be generalized to other applicatives?

眉间皱痕 提交于 2019-12-13 09:46:50

问题


In Maybe applicative, <*> can be implemented based on fmap. Is it incidental, or can it be generalized to other applicative(s)?

(<*>)   ::  Maybe   (a  ->  b)  ->  Maybe   a   ->  Maybe   b
Nothing <*> _   =   Nothing
(Just   g)  <*> mx  =   fmap    g   mx

Thanks.

See also In applicative, how can `<*>` be represented in terms of `fmap_i, i=0,1,2,...`?


回答1:


It cannot be generalized. A Functor instance is unique:

instance Functor [] where
    fmap = map

but there can be multiple valid Applicative instances for the same type constructor.

-- "Canonical" instance: [f, g] <*> [x, y] == [f x, f y, g x, g y]
instance Applicative [] where
    pure x = [x]
    [] <*> _ = []
    (f:fs) <*> xs = fmap f xs ++ (fs <*> xs)

-- Zip instance: [f, g] <*> [x, y] == [f x, g y]
instance Applicative [] where
    pure x = repeat x
    (f:fs) <*> (x:xs) = f x : (fs <*> xs)
    _ <*> _ = []

In the latter, we neither want to apply any single function from the left argument to all elements of the right, nor apply all the functions on the left to any single element on the right, making fmap useless.



来源:https://stackoverflow.com/questions/57220345/is-the-implementation-of-based-on-fmap-special-to-maybe-applicative-or-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!