4

Is there a >>= for functions of two arguments? Something like

bind2 :: m a -> m b -> (a -> b -> m c) -> m c
Kwarrtz
  • 2,693
  • 15
  • 24
  • 2
    `Control.Monad.liftM2` -- with arguments in a different (& usually more convenient) order – luqui Aug 29 '15 at 01:20
  • 1
    @luqui: `liftM2` takes a function of type `a -> b -> c`, whereas this hypothetical `bind2` takes a function of type `a -> b -> m c`. – icktoofay Aug 29 '15 at 01:20
  • 9
    Oops you're right, sloppy reading. No there isn't, unfortunately. You can use `join (liftM2 op x y)`. – luqui Aug 29 '15 at 01:22
  • 1
    @luqui +1 for `join` and `liftM2`. – Kwarrtz Aug 29 '15 at 01:31
  • 2
    possible duplicate of [Combine monads that take multiple arguments](http://stackoverflow.com/questions/22115472/combine-monads-that-take-multiple-arguments) – Mirzhan Irkegulov Aug 29 '15 at 08:58
  • It's a [duplicate](http://stackoverflow.com/questions/27134349/extracting-nested-monadic-result-m-m-a-m-a). But the question is stated clearer here. – effectfully Aug 29 '15 at 09:56
  • @user3237465 However the answer to the other question is much more complete. – Bakuriu Aug 29 '15 at 10:13
  • I'm new to SO so I don't know how the duplicate system works, but it is possible to merge two questions? – Kwarrtz Sep 04 '15 at 17:31

1 Answers1

6

I don't know what clever combinators you could use to build this out of the standard library, but at the risk of stating the obvious it is pretty easy to implement yourself:

bind2 :: Monad m => (a -> b -> m c) -> m a -> m b -> m c
bind2 f ma mb = do
  a <- ma
  b <- mb
  f a b

> bind2 (\a b -> [a,b]) [1,2,3] [4,5,6]
[1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6]
amalloy
  • 89,153
  • 8
  • 140
  • 205