Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine results within a monad without do

I have a snippet of code which can abstractly be described as this:

foobar = do
  foo <- getFoo
  bar <- getBar
  return $ foo ++ bar

It feels like there must be a nice way to combine foo and bar that doesn’t require four lines of do notation – some infix operator I can apply directly to getFoo and getBar maybe (perhaps specifying (++) as a combining function, but given that the results are a Monoid I shouldn’t really have to…) – but I can’t find anything like this.

I searched Hoogle for things like Monad m => (a -> a -> a) -> m a -> m a -> m a and Monad m, Monoid a => m a -> m a -> m a but came up empty.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a combine function/operator like this?

>Solution :

Applicative notation is rather popular:

foobar = (++) <$> getFoo <*> getBar

This naturally extends to n-ary functions. The expression f <$> action1 <*> ... <*> actionN works under the following hypotheses:

-- F is any applicative (including monads)
actioni :: F ti   -- for i in 1..N
f :: t1 -> t2 -> ... -> tN -> r

in which case

f <$> action1 <*> ... <*> actionN :: F r
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading