Skip to content
This repository was archived by the owner on Mar 29, 2021. It is now read-only.

Monad Transformer instances#76

Merged
kubukoz merged 3 commits intomasterfrom
feature/monad-transformer-instances
Dec 21, 2019
Merged

Monad Transformer instances#76
kubukoz merged 3 commits intomasterfrom
feature/monad-transformer-instances

Conversation

@gvolpe
Copy link
Copy Markdown
Member

@gvolpe gvolpe commented Dec 21, 2019

I was working on some examples using Console and Monad Transformers and I figured it makes sense to provide default instances, given some F[_]: Applicative: Console].

@gvolpe gvolpe added the enhancement New feature or request label Dec 21, 2019
@gvolpe gvolpe requested a review from kubukoz December 21, 2019 15:45
@kubukoz
Copy link
Copy Markdown
Member

kubukoz commented Dec 21, 2019

I would normally just mapK when defining an instance (or use .stdio[EitherT[...]], but I guess there's nothing dangerous about providing inductive instances for transformers. Let's do it :)

@kubukoz kubukoz merged commit 21c0576 into master Dec 21, 2019
@kubukoz kubukoz deleted the feature/monad-transformer-instances branch December 21, 2019 16:47
@gvolpe
Copy link
Copy Markdown
Member Author

gvolpe commented Dec 21, 2019

It comes in handy when you already have the IO instance in scope using import cats.effect.Console.implicits._. You get the transformer instance for free :)

In my case, I have two programs in the same file:

def program[F[_]: Console](implicit M: MonadState[F, FooState]): F[Unit] =
  for {
    current <- M.get
    _ <- Console[F].putStrLn(current)
    _ <- M.set(FooState("foo"))
    updated <- M.get
    _ <- Console[F].putStrLn(updated)
  } yield ()

val p1: IO[Unit] =
  program[StateT[IO, FooState, *]].run(FooState("mt")).void

val p2: IO[Unit] =
  Ref.of[IO, FooState](FooState("bar")).flatMap { ref =>
    ref.runState { implicit ms =>
      program[IO]
    }
  }

In this way, we can be sure the underlying Console[IO] instance is the same one the transformer gets.

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

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants