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和单子的情况下实现这一目标。
答案 0 :(得分:4)
它可以在Control.Applicative中使用<$>
和<*>
运算符来做到这一点:
sequenceAL :: Applicative f => [f a] -> f [a]
sequenceAL [] = pure []
sequenceAL (x:xs) = (:) <$> x <*> sequenceAL xs