这不应该在某个图书馆吗? [英] Shouldn't this be in a library somewhere?
问题描述
我正在编写一些代码来生成大量随机值并将它们添加到结构中,并且我需要一种机制来链接相同的IO操作。所以,我写了这个:
I was writing some code to generate a lot of random values and add them to a structure, and I needed a mechanism to chain up identical IO actions. So, I wrote this:
chain :: Monad m => Int -> (a -> m a) -> a -> m a
chain 0 _ a = return a
chain n f a = f =<< chain (n-1) f a
我怀疑这应该在某个图书馆某处,但我无法在Control.Monad中找到它。这个功能已经写好了吗?有没有更简单的方法来做到这一点?
I get a suspicion that this should be in some library somewhere, but I couldn't find it in Control.Monad. Is this function already written? Is there an easier way to do this?
推荐答案
我不知道它是否存在某处,但它可以被整齐地定义as:
I don't know if it exists somewhere, but it can be neatly defined as:
chain :: Monad m => Int -> (c -> m c) -> c -> m c
chain n = foldr (>=>) return . replicate n
中有几个潜在有用的函数(<$ c)例如,$ c> foldr(> =>)return 是 concatM
),尽管不完全是链
。
monad-loops has a few potentially useful functions in that vein (foldr (>=>) return
, for instance, is concatM
), though not exactly your chain
.
这篇关于这不应该在某个图书馆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!