2 ms·
> not all monads support a coalescing operation like Promise.all. Actually, they do. Haskell calls it sequence :: (Traversable t, Monad m) => t (m a) -> m (t a
by yorwba 9y ago
> not all monads support a coalescing operation like Promise.all.
Actually, they do. Haskell calls it sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) [1]
It works by consuming the structure outside the monad and rebuilding it inside. A possible implementation specialized for lists is
sequence [] = return []
sequence (h:t) = do
h' <- h
t' <- sequence t
return (h':t')
[1] http://hackage.haskell.org/package/base-4.10.0.0/docs/Prelude.html#v:sequence http://hackage.haskell.org/package/base-4.10.0.0/docs/Prelud...
- charliesome 9y agoSorry, I should've been more clear. You're right - you can absolutely build sequence out of the bind operation for any monad. Promise.all is not just sequence though, there's some additional subtleties to it. In particular the fail-fast behaviour: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all#Promise.all_fail-fast_behaviour https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... That's the kind of fundamental coalescing operation that you cannot implement with bind on plain monads.