gpt4 book ai didi

haskell - 了解 `sequence_`

转载 作者:行者123 更新时间:2023-12-02 16:04:13 24 4
gpt4 key购买 nike

All About Monads解释sequence_:

The sequence_ function (notice the underscore) has the same behavior as sequence but does not return a list of results. It is useful when only the side-effects of the monadic computations are important.

然后,查看TestSequence.hs:

import Control.Monad

f :: String -> IO ()
f x = print x

run :: [String] -> IO ()
run xs = sequence_ . map f $ xs

我可以运行它:

λ: run ["foo", "bar"]
"foo"
"bar"

sequence_ 是否在每个 IO () 上调用 unsafePerformIO 来获取结果,即 ()

而且,sequence_ 是否不受欢迎?或者对于 IO Monad 来说,只是简单地使用“在世界末日”来运行一系列 IO 操作?

最佳答案

不,它不会在每个 IO () 操作上调用 unsafePerformIO。事实上,它的类型甚至不特定于 IO:

sequence_ :: (Monad m, Foldable t) => t (m a) -> m ()

在旧的库中,当它特定于列表(而不是对所有 Foldable 通用)时,它是通过以下完全可读的方式实现的:

sequence_ [] = return ()
sequence_ (x:xs) = x >> sequence_ xs

绝对不气馁; sequence_(及其老大哥 mapM_)非常有用,以至于它甚至是我解释为什么 Monad 的激励示例之一作为一个抽象是有用的。

关于haskell - 了解 `sequence_`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33338097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com