Tim*_*Tim -3 haskell applicative maybe
在可能的情况下,<*>可以基于实现fmap。它是偶然的,还是可以推广到其他应用程序?
(<*>) :: Maybe (a -> b) -> Maybe a -> Maybe b
Nothing <*> _ = Nothing
(Just g) <*> mx = fmap g mx
Run Code Online (Sandbox Code Playgroud)
谢谢。
它不能一概而论。一个Functor实例是唯一的:
instance Functor [] where
fmap = map
Run Code Online (Sandbox Code Playgroud)
但是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)
_ <*> _ = []
Run Code Online (Sandbox Code Playgroud)
在后者中,我们既不希望将left参数中的任何单个函数应用于右边的所有元素,也不希望将left中的所有函数应用于右边的任何单个元素,从而变得fmap毫无用处。