Skip to content

Instantly share code, notes, and snippets.

@slouc
Last active May 3, 2019 09:53
Show Gist options
  • Save slouc/dfd693f119c53104c3e2d3004bdfb37b to your computer and use it in GitHub Desktop.
Save slouc/dfd693f119c53104c3e2d3004bdfb37b to your computer and use it in GitHub Desktop.
import scalaz._
import Scalaz._
import scalaz.{Applicative, \/}
def selectA[F[_]: Applicative, A, B](s: F[A \/ B])(f: => F[A => B]): F[B] =
(s |@| f)(_.leftMap(_).merge)
def selectM[F[_]: Monad, A, B](s: F[A \/ B])(f: => F[A => B]): F[B] =
s flatMap {
case -\/(a) => f.map(_(a))
case \/-(b) => Monad[F].pure(b)
}
val s: Option[Int \/ String] = Option(\/-("foo"))
def f: Option[Int => String] = {
println("side-effect!")
Option((i: Int) => i.toString)
}
val applicativeSelector = selectA(s) _
val monadSelector = selectM(s) _
println(applicativeSelector(f)) // prints "side-effect!"
println(monadSelector(f)) // doesn't print "side-effect!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment