Victor
Victor

Reputation: 586

Is there a `m a -> (a -> m b) -> m a` function type in haskell?

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!

Upvotes: 2

Views: 313

Answers (2)

Cubic
Cubic

Reputation: 15693

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.

Upvotes: 3

Alexey Romanov
Alexey Romanov

Reputation: 170835

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

Though jozefg's solution is simpler.

Upvotes: 10

Related Questions