为列表实现 sequenceAL
Implementing sequenceAL for lists
Typeclassopedia(Haskell Wiki)在 Applicative 部分有这个练习:
Implement a function
sequenceAL :: Applicative f => [f a] -> f [a]
我只能这样做,如果使用 do 表示法(需要将 Monad f 添加到上下文中:
sequenceAL :: (Monad f, Applicative f) => [f a] -> f [a]
sequenceAL [] = pure []
sequenceAL (x:xs) = do
y <- x
ys <- sequenceAL xs
pure ([y] ++ ys)
如何在不使用 do-notation 和 monad 的情况下实现这一目标。
可以在Control.Applicative中使用<$>
和<*>
运算符来实现:
sequenceAL :: Applicative f => [f a] -> f [a]
sequenceAL [] = pure []
sequenceAL (x:xs) = (:) <$> x <*> sequenceAL xs
Typeclassopedia(Haskell Wiki)在 Applicative 部分有这个练习:
Implement a function
sequenceAL :: Applicative f => [f a] -> f [a]
我只能这样做,如果使用 do 表示法(需要将 Monad f 添加到上下文中:
sequenceAL :: (Monad f, Applicative f) => [f a] -> f [a]
sequenceAL [] = pure []
sequenceAL (x:xs) = do
y <- x
ys <- sequenceAL xs
pure ([y] ++ ys)
如何在不使用 do-notation 和 monad 的情况下实现这一目标。
可以在Control.Applicative中使用<$>
和<*>
运算符来实现:
sequenceAL :: Applicative f => [f a] -> f [a]
sequenceAL [] = pure []
sequenceAL (x:xs) = (:) <$> x <*> sequenceAL xs