Home > Software engineering >  Is there a name in Haskell for `[m a] -> m a`?
Is there a name in Haskell for `[m a] -> m a`?

Time:11-28

Let's say I have a Future monad, so Future a represents an a that may or may not yet be available. Then sequenceA automatically gives me the semantics "wait for all of these futures to be ready and give me all their values":

sequenceA :: [Future a] -> Future [a]

This is something like a logical AND, since it doesn't become ready until all the inputs are ready. Carrying that metaphor further, we could define the logical OR: "become ready with the value of the first input that becomes ready".

firstReady: [Future a] -> Future a

Does this metaphore generalize to other monads/traversables? Is there a standard name for this operation?

CodePudding user response:

The async package exposes the Concurrently newtype which has an Alternative instance that gives rise to the "return the first thing that finishes" behavior.

The firstReady function is called asum :: [Concurrently a] -> Concurrently a.

But note that Concurrently doesn't have a monad instance, because it wouldn't be possible to satisfy the law:

m1 <*> m2 = m1 >>= (\x1 -> m2 >>= (\x2 -> return (x1 x2)))

(The <*> runs both its arguments at the same time but the >>= is forced to run its first argument fully before it can start running its second argument.)

  • Related