Kev*_*ith 4 haskell applicative
对于List,为什么right apply (*>)表现为重复并附加第二个参数n次数,n第一个参数的长度在哪里?
ghci> [1,2,3] *> [4,5]
[4,5,4,5,4,5]
Run Code Online (Sandbox Code Playgroud)
该*>运营商的定义,默认情况下,作为
xs *> ys = id <$ xs <*> ys
Run Code Online (Sandbox Code Playgroud)
默认情况下,它会转换为
const id <$> xs <*> ys
Run Code Online (Sandbox Code Playgroud)
也就是说,它将xswith的每个元素替换id为get xs'然后计算xs' <*> ys.[]是一个Monad实例,在哪里(=<<) = concatMap.Applicative规定Applicative与Monad实例之间关系的法则之一:
pure = return
fs <*> as = fs `ap` as = fs >>= \f -> as >>= \a -> f a
Run Code Online (Sandbox Code Playgroud)
对于列表,这是
fs <*> as = [f a | f <- fs, a <- as]
Run Code Online (Sandbox Code Playgroud)
因此*>,列表最终由Monad实例确定.
请注意,列表还有另一个非常明智的Applicative实例,可以通过以下新类型获得Control.Applicative:
newtype ZipList a = ZipList [a]
instance Applicative ZipList where
pure = repeat
(<*>) = zipWith ($)
Run Code Online (Sandbox Code Playgroud)