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.
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