Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Last active February 19, 2021 19:04
Show Gist options
  • Select an option

  • Save joshuakfarrar/3d08db611492a9c35ac4a55c37280390 to your computer and use it in GitHub Desktop.

Select an option

Save joshuakfarrar/3d08db611492a9c35ac4a55c37280390 to your computer and use it in GitHub Desktop.
use monad transformers for great elegance!
import cats.data.OptionT
import cats.implicits._
/*
* in my domain, the confirmation algebra provides Confirmable,
* which is parameterized over the type of id of the thing, probably
* a user, to be confirmed, and the type of the confirmation token
*/
type C = Confirmable[UUID, SecureRandomId]
def getConfirmableFromToken(token: SecureRandomId): OptionT[F, C] = for {
(userId, confirmation) <- confirmationService.getByToken(token)
user <- userService.find(userId)
} yield ConfirmableUser(user, confirmation)
@joshuakfarrar

Copy link
Copy Markdown
Author

OptionT[F[_], A] is a monad transformer, representing F[Option[A]], where F represents an arbitrary functor (or monad, because monads are just composable functors!), and A is some type of thing wrapped by that functor, e.g. OptionT[IO, User] encodes IO[Option[User]]. Monad transformers compose neatly and with them you can avoid some boilerplate around monad composition with .flatMap and .map

For more information on this particular implementation of OptionT, see the Cats documentation: https://typelevel.org/cats/datatypes/optiont.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment