typelevel / typelevel/cats

Additional example for FreeT in docs

Open
#2,818 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Scala
Stars
5.5k
Forks
1.2k
Avg merge
2d 10h
Merged PRs (30d)
5

Description

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)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the existing FreeT documentation and its State monad example, then review the proposed Future and Option example in the issue. Add a basic example covering the shown FreeT operations and interpreters, and confirm the documented result is correct and readable.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.