Skip to content

Instantly share code, notes, and snippets.

@ncfavier
Last active November 16, 2021 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncfavier/4ce6a6ff00286b880512dbc2704e8d44 to your computer and use it in GitHub Desktop.
Save ncfavier/4ce6a6ff00286b880512dbc2704e8d44 to your computer and use it in GitHub Desktop.
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 words,

  • 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