Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional example for FreeT in docs #2818

Open
mtsokol opened this issue Apr 28, 2019 · 1 comment
Open

Additional example for FreeT in docs #2818

mtsokol opened this issue Apr 28, 2019 · 1 comment

Comments

@mtsokol
Copy link
Contributor

mtsokol commented Apr 28, 2019

Hi,
I have recently used FreeT and found that docs provide only pretty specific example with State monad.

Would you mind accepting docs PR with additional basic Future Option example?

After consulting on gitter I ended up with additional transformation for Option ~> OptionT, which I am not sure.

import cats.free._
import cats._
import cats.data._
import cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

sealed trait Ctx[A]

case class Action(value: Int) extends Ctx[Int]

def op1: FreeT[Ctx, Option, Int] =
  FreeT.liftF[Ctx, Option, Int](Action(7))

def op2: FreeT[Ctx, Option, Int] =
  FreeT.liftT[Ctx, Option, Int](Some(4))

def op3: FreeT[Ctx, Option, Int] =
  FreeT.pure[Ctx, Option, Int](1)

val opComplete: FreeT[Ctx, Option, Int] =
  for {
    a <- op1
    b <- op2
    c <- op3
  } yield a + b + c


// ----interpreters----

type OptFut[A] = OptionT[Future, A]

def futureInterpreter: Ctx ~> OptFut = new (Ctx ~> OptFut) {
  def apply[A](fa: Ctx[A]): OptFut[A] = {
    fa match {
      case Action(value) => OptionT.liftF(Future(value))
    }
  }
}

def optFutLift: Option ~> OptFut = new (Option ~> OptFut) {
  def apply[A](fa: Option[A]): OptFut[A] = {
    fa match {
      case Some(value) =>
        OptionT(Future(Option(value)))
      case None =>
        OptionT.none
    }
  }
}

val hoisted = opComplete.hoist(optFutLift)
val evaluated = hoisted.foldMap(futureInterpreter)

val future = evaluated.value
// Some(12)
@kailuowang
Copy link
Contributor

👍 for Option. Mix feelings for Future. Future is widely used but we should be encouraging people to move away from it. Maybe we should add a FAQ item on this topic?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants