Last active
March 12, 2018 16:52
-
-
Save neko-kai/9f1d8a5ebb00fd6052e11cfb1530a898 to your computer and use it in GitHub Desktop.
.eff fork+discard function for cats Arrow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//import scalaz._ | |
//import scalaz.syntax.arrow._ | |
// | |
//def eff[F[_, _]: Arrow, A, B](a: F[A, B])(effFn: F[B, Unit]): F[A, B] = { | |
// val z = Arrow[F].arr(identity[B]) &&& Arrow[F].arr(identity[B]) | |
// | |
// a >>> z >>> effFn.second[B].mapsnd(_._1) | |
//} | |
import cats.arrow._ | |
import cats.syntax.functor._ | |
import cats.syntax.profunctor._ | |
import cats.syntax.strong._ | |
import cats.syntax.compose._ | |
import scala.language.higherKinds | |
def effImpl[F[_, _]: Arrow, A, B](a: F[A, B])(eff: F[B, Unit]): F[A, B] = { | |
val forkedA: F[A, (B, B)] = | |
a.rmap(mkTuple) | |
val effOnFirst: F[(B, B), (Unit, B)] = | |
eff.first | |
forkedA >>> effOnFirst >>> discardFirst | |
} | |
def mkTuple[A](a: A): (A, A) = | |
(a, a) | |
def discardFirst[F[_, _]: Arrow, A, B]: F[(A, B), B] = { | |
Arrow[F].lift(_._2) | |
} | |
implicit class ArrowEff[F[_, _]: Arrow, A, B](fab: F[A, B]) { | |
def eff(eff: F[B, Unit]): F[A, B] = { | |
effImpl(fab)(eff) | |
} | |
} | |
object Abc { | |
import cats.instances.all._ | |
def a = { x: Int => x + 1 } | |
.andThen(_ * 5) | |
.andThen(_ ^ 2) | |
.eff(x => println(s"Current value: $x")) | |
.andThen(Seq.fill(_)('Z')) | |
.andThen(_.mkString) | |
.eff(println(_)) | |
.andThen(_.length) | |
.eff(println(_)) | |
.apply(1) | |
def b = { x: Int => x + 1 } | |
.>>>(_ * 5) | |
.>>>(_ ^ 2) | |
.eff(x => println(s"Current value: $x")) | |
.>>>(Seq.fill(_)('Z')) | |
.>>>(_.mkString) | |
.eff(println(_)) | |
.>>>(_.length) | |
.eff(println(_)) | |
.apply(1) | |
def c = { x: Int => x + 1 } | |
.map(_ * 5) | |
.map(_ ^ 2) | |
.eff(x => println(s"Current value: $x")) | |
.map(Seq.fill(_)('Z')) | |
.map(_.mkString) | |
.eff(println(_)) | |
.map(_.length) | |
.eff(println(_)) | |
.apply(1) | |
} | |
Abc.a | |
Abc.b | |
Abc.c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment