基于fmap的< *>的实现是否可能是可应用的,还是可以推广到其他应用? [英] Is the implementation of `<*>` based on `fmap` special to Maybe applicative or can it be generalized to other applicatives?
问题描述
在可能的情况下,可以基于fmap
实现<*>
.是偶然的,还是可以推广到其他应用程序?
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
谢谢.
另请参阅在适用情况下,如何用fmap_i,i = 0,1,2,...`来表示< *?
推荐答案
它不能一概而论. Functor
实例是唯一的:
It cannot be generalized. A Functor
instance is unique:
instance Functor [] where
fmap = map
,但是对于同一类型构造函数,可以有多个有效的Applicative
实例.
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)
_ <*> _ = []
在后者中,我们既不想将left参数中的任何单个函数应用到右边的所有元素,也不想将左边的所有函数应用到右边的任何单个元素,从而使fmap
没有用.
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.
这篇关于基于fmap的< *>的实现是否可能是可应用的,还是可以推广到其他应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!