在 也许适用,<*>
可以基于fmap
实现。它是偶然的,还是可以推广到其他应用
(<*>) :: Maybe (a -> b) -> Maybe a -> Maybe b
Nothing <*> _ = Nothing
(Just g) <*> mx = fmap g mx
谢谢。
参见 在应用中,"<*>"如何用"fmap_i,i=0,1,2,..."来表示?
它不能一概而论。Functor
实例是唯一的:
instance Functor [] where
fmap = map
但是,同一类型构造函数可以有多个有效的 Applicative
实例。
-- "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)
_ <*> _ = []
在后者中,我们既不想将左参数中的任何单个函数应用于右参数的所有元素,也不想将左边的所有函数应用于右边的任何单个元素,从而使fmap
毫无用处。