對可摺疊結構的每個元素執行副作用
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