Skip to content

Instantly share code, notes, and snippets.

@ncfavier

ncfavier/traversoids.md

Last active Dec 2, 2019
Embed
What would you like to do?
Summary of Haskell's traversal functions
traverse   :: (Traversable t, Applicative f) => (a -> f b) -> t a        -> f (t b)
traverse_  :: (Foldable    t, Applicative f) => (a -> f b) -> t a        -> f ()
for        :: (Traversable t, Applicative f) => t a        -> (a -> f b) -> f (t b)
for_       :: (Foldable    t, Applicative f) => t a        -> (a -> f b) -> f ()
sequenceA  :: (Traversable t, Applicative f) => t (f a)                  -> f (t a)
sequenceA_ :: (Foldable    t, Applicative f) => t (f a)                  -> f ()
mapM       :: (Traversable t, Monad       m) => (a -> m b) -> t a        -> m (t b)
mapM_      :: (Foldable    t, Monad       m) => (a -> m b) -> t a        -> m ()
forM       :: (Traversable t, Monad       m) => t a        -> (a -> m b) -> m (t b)
forM_      :: (Foldable    t, Monad       m) => t a        -> (a -> m b) -> m ()
sequence   :: (Traversable t, Monad       m) => t (m a)                  -> m (t a)
sequence_  :: (Foldable    t, Monad       m) => t (m a)                  -> m ()

In short,

  • for is traverse with its arguments flipped (flip traverse)
  • sequenceA is traverse id
  • one can obtain the monadic variant of any of these functions using the following (confusing) renaming scheme: traverse → mapM, for → forM, sequenceA → sequence
  • appending an underscore to any of these functions gives a variant that discards its result value (just like using () <$). Since there is no need to reconstruct the structure of t inside of f, the constraint is relaxed from Traversable to Foldable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.