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?
The
asyncpackage exposes theConcurrentlynewtype which has anAlternativeinstance that gives rise to the "return the first thing that finishes" behavior.The
firstReadyfunction is calledasum :: [Concurrently a] -> Concurrently a.But note that
Concurrentlydoesn't have a monad instance, because it wouldn't be possible to satisfy the law:(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.)