【发布时间】:2018-06-05 13:51:27
【问题描述】:
我从 Hutton's Programming in Haskell 中阅读了有关 Haskell 中 Applicative 的信息。为了更好地理解它,我为列表的Applicative 提出了以下定义:
-- Named as pure' and "app" to avoid confusion with builtin versions
class Applicative' f where
pure' :: a -> f a
app :: f (a->b) -> f a -> f b
instance Applicative' [] where
pure' x = [x]
app _ [] = []
app [g] (x:xs) = [(g x)] ++ app [g] xs
app (g:gs) (x:xs) = [(g x)] ++ app gs xs
-- fmap functions could be defined as:
fmap1' :: (Applicative' f)=>(a->b) -> f a -> f b
fmap1' g x = app (pure' g) x
fmap2' :: (Applicative' f)=>(a->b->c) -> f a -> f b -> f c
fmap2' g x y = app (app (pure' g) x) y
fmap3' :: (Applicative' f)=>(a->b->c->d) -> f a -> f b -> f c -> f d
fmap3' g x y z = app (app (app (pure' g) x) y) z
fmap2'的使用示例如下:
Ok, one module loaded.
*Main> g = \x y -> x*y
*Main> arr1 = [1,2,3]
*Main> arr2 = [4,5,6]
*Main> fmap2' g arr1 arr2
[4,10,18]
*Main>
但Applicative函数<*>的标准定义为:
gs <*> xs = [g x | g <- gs, x <- xs]
因此导致
pure (*) <*> [1,2], [3,4]
[3,4,6,8]
我想知道为什么它以for all arr1, for all arr2, apply function 而不是take corresponding elements arr1, arr2 apply function 的方式定义。
我想第一个定义可能更有用?这种选择有什么具体原因吗?
【问题讨论】:
-
@duplode 我认为这不是完全重复的,因为这里询问的实例并不是真正的
ZipList(尽管这似乎是想法)。 -
@leftaroundabout 哦,
(:[])与repeat的问题也出现在这里。好眼力;重新开放。 (为了完整起见,建议的问题是Why ZipList is not the default Applicative Instance for List。) -
List 已经有一个 Monad 的实现,它强制应用程序实例(
ap我可以用return和>>=来编写任何 Monad 并且与<*>相同。
标签: haskell applicative