So >>= :: m a -> (a -> m b) -> m b and >> :: m a -> m b -> m b.

whereas <* :: f a -> f b -> f a.

But I want something that does m a -> (a -> m b) -> m a, i.e. actually discards the computation result and keeps the original. In my case, this computation result is just an IO operation that returns () so I just need to pass the original value along.

Is there such a function? If not, how do I compose one? Haven't managed to figure it out. Thanks!

有帮助吗?

解决方案

discardResult mx mf = do x <- mx
                         mf x
                         return x

Though jozefg's solution is simpler.

其他提示

discard :: Monad m => m a -> (a -> m b) -> m a
discard g f = g >>= ((>>) <$> f <*> return)

Uses the Applicative instance of (->) to make it a little shorter, but is otherwise equivalent to Alexey's answer. Of course this requires Control.Applicative but since you mentioned <* I figured you already had that one.

E.g: discard getLine print reads a line, prints it and then returns the string read.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top