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

added FreeT basic example #2819

Merged
merged 2 commits into from
May 21, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion docs/src/main/tut/datatypes/freemonad.md
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ In the following example a basic console application is shown.
When the user inputs some text we use a separate `State` monad to track what the user
typed.

As we can observe in this case `FreeT` offers us a the alternative to delegate denotations to `State`
As we can observe in this case `FreeT` offers us the alternative to delegate denotations to `State`
monad with stronger equational guarantees than if we were emulating the `State` ops in our own ADT.

```tut:book
Expand Down Expand Up @@ -560,6 +560,66 @@ val initialState = Nil
val (stored, _) = state.run(initialState).value
```

Another example is more basic usage of `FreeT` with some context `Ctx` for which we provide `Try` interpreter,
combined with `OptionT` for reducing boilerplate.

```tut:book
import cats.free._
import cats._
import cats.data._
import cats.implicits._
import scala.util.Try

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


/* Our interpreters */

type OptTry[A] = OptionT[Try, A]

def tryInterpreter: Ctx ~> OptTry = new (Ctx ~> OptTry) {
def apply[A](fa: Ctx[A]): OptTry[A] = {
fa match {
case Action(value) =>
OptionT.liftF(Try(value))
}
}
}

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

val hoisted = opComplete.hoist(optTryLift)
val evaluated = hoisted.foldMap(tryInterpreter)
val result = evaluated.value
```

## Future Work (TODO)

There are many remarkable uses of `Free[_]`. In the future, we will
Expand Down