对可折叠结构的每个元素执行副作用
traverse_
为 Foldable
结构中的每个元素执行 Applicative
动作。它忽略了动作的结果,只保留了副作用。 (对于不丢弃结果的版本,请使用 Traversable
。)
-- using the Writer applicative functor (and the Sum monoid)
ghci> runWriter $ traverse_ (\x -> tell (Sum x)) [1,2,3]
((),Sum {getSum = 6})
-- using the IO applicative functor
ghci> traverse_ putStrLn (Right "traversing")
traversing
ghci> traverse_ putStrLn (Left False)
-- nothing printed
for_
是 traverse_
,翻转了参数。它类似于命令式语言中的 foreach
循环。
ghci> let greetings = ["Hello", "Bonjour", "Hola"]
ghci> :{
ghci| for_ greetings $ \greeting -> do
ghci| print (greeting ++ " Stack Overflow!")
ghci| :}
"Hello Stack Overflow!"
"Bonjour Stack Overflow!"
"Hola Stack Overflow!"
sequenceA_
将一个完整的 Applicative
动作折叠成一个动作,忽略了结果。
ghci> let actions = [putStrLn "one", putStLn "two"]
ghci> sequenceA_ actions
one
two
traverse_
被定义为等同于:
traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
traverse_ f = foldr (\x action -> f x *> action) (pure ())
sequenceA_
定义为:
sequenceA_ :: (Foldable t, Applicative f) -> t (f a) -> f ()
sequenceA_ = traverse_ id
此外,当 Foldable
也是 Functor
时,traverse_
和 sequenceA_
具有以下关系:
traverse_ f = sequenceA_ . fmap f