Skip to content

Instantly share code, notes, and snippets.

@Daenyth
Last active June 25, 2024 13:05
Show Gist options
  • Save Daenyth/e7ed8ca548b7f60cfeb924eb0e9a8811 to your computer and use it in GitHub Desktop.
Save Daenyth/e7ed8ca548b7f60cfeb924eb0e9a8811 to your computer and use it in GitHub Desktop.
Scala (cats) map/traverse parallels

Parallels between map and similar functions

map          :: F[A] => (A =>     B)   => F[B]
flatMap      :: F[A] => (A =>   F[B])  => F[B]
traverse     :: G[A] => (A =>   F[B])  => F[G[B]]
flatTraverse :: G[A] => (A => F[G[B]]) => F[G[B]]
traverse_    :: F[A] => (A =>   F[B])  => F[Unit]

traverse vs sequence

Both let you "flip" nested effects inside out

traverse  :: G[A] => (A => F[B]) => F[G[B]]
sequence  :: G[F[A]]             => F[G[A]]

You can also run just the effects and ignore the value

traverse_ :: F[A] => (A => F[B]) => F[Unit]
sequence_ :: G[F[A]]             => F[Unit]

Both functions can be defined in terms of each other

fa.traverse(f) == fa.map(f).sequence
fa.sequence    == fa.traverse(identity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment