Skip to content

Commit

Permalink
Added flatMapK to FreeT (#3235)
Browse files Browse the repository at this point in the history
* Added flatMapK to FreeT (where it is useful, unlike with Free where it's simply foldMap)

* Removed mixed bounds syntax
  • Loading branch information
djspiewak authored Feb 25, 2020
1 parent 8501d0b commit 2e12f4d
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions free/src/main/scala/cats/free/FreeT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,19 @@ sealed abstract class FreeT[S[_], M[_], A] extends Product with Serializable {
Suspend(mn(m))
}

/**
* Modify the context `M` using the transformation `mn`, flattening the free
* suspensions into the outer.
*/
def flatMapK[N[_]](mn: M ~> FreeT[S, N, *])(implicit S: Functor[S], N: Monad[N]): FreeT[S, N, A] = {
def loop(ftft: FreeT[S, FreeT[S, N, *], A]): FreeT[S, N, A] =
ftft.resume.flatMap { e =>
e.fold(sft => FreeT.liftF[S, N, FreeT[S, FreeT[S, N, *], A]](sft).flatMap(loop(_)), a => FreeT.pure(a))
}

loop(mapK(mn))
}

/** Binds the given continuation to the result of this computation. */
final def flatMap[B](f: A => FreeT[S, M, B]): FreeT[S, M, B] =
FlatMapped(this, f)
Expand Down

0 comments on commit 2e12f4d

Please sign in to comment.