Skip to content

Instantly share code, notes, and snippets.

@telekosmos
Created February 11, 2022 19:38
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 telekosmos/32fd270c45cac6ce2fc20458d4bccc33 to your computer and use it in GitHub Desktop.
Save telekosmos/32fd270c45cac6ce2fc20458d4bccc33 to your computer and use it in GitHub Desktop.
"Equations" to define and request - response as a Kleisli in http4s

http4s defines a web application as a function of requests and response, just like:

Request => Response

As we are accessing to some resource like dbs, files or even the network, there will be involved some effect in the response, so:

Request => F[Response]

Being F the (side) effect affecting the response.

Also, some times there won't be response at all:

Request => F[Option[Response]]

The way http4s chose to represent this function is via a Kleisli monad, which for a types A, B and a type constructor F[_] produces A => F[B] and is defined like:

Kleisli[F[_], A, B] to produce A => F[B]

http4s uses a Kleili to define the Request/Response function, the routes:

Kleisli[OptionT[F, *], Request, Response]

Given the OptionT is a monad transformer defined as OptionT[F, A] -> F[Option[A]] (OptionT[Future, String] is Future[Option[String]]), the Kleisli just above is translated as:

Request => OptionT[F, Response]

which is

Request => F[Option[Response]]

which is the definition of a route aka Request/Response round.

@telekosmos
Copy link
Author

From the dirty notes:

  Request => Response
  Request => F[Response]
  Request => F[Option[Response]]
  (Kleisli[F[_], A, B] -> A => F[B])
  Kleisli[F[_], Request, Option[Response]] -> Request => F[Option[Response]]
  (OptionT[F, Response] == F[Option[String]])
  Kleisli[OptionT[F, *], Request, Response] -> Request => OptionT[F, Response] -> Request => F[Option[Response]]

  which is a synonym of HttpRoutes[F]

  OptionT[Future, String] = Future[Option[String]]

  Kleisli[OptionT[F, *], Request, Response] (Kleisli[F[_], A, B] -> A => F[B])
  Kleisli[F[_], Request, Response] -> Request => F[Response]
  Request => OptionT[F, Response]
  Request => F[Option[Response]]
  if F is IO
  Request => IO[Option[Response]]

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