基于"fmap"的"<*>"的实现是否特别适用于"可能适用",或者是否可以推广到其他应用?



在 也许适用,<*>可以基于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毫无用处。

相关内容

最新更新