Skip to content

Instantly share code, notes, and snippets.

@aoiroaoino
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aoiroaoino/a279ec9b779a805f898c to your computer and use it in GitHub Desktop.
Save aoiroaoino/a279ec9b779a805f898c to your computer and use it in GitHub Desktop.
name := "OptionValueAccessor"
scalaVersion := "2.11.6"
libraryDependencies ++= Seq(
"com.github.julien-truffaut" %% "monocle-core" % "1.1.1",
"com.github.julien-truffaut" %% "monocle-macro" % "1.1.1"
)
scalacOptions ++= Seq(
"-feature",
"-language:higherKinds",
"-language:postfixOps"
)
object EDCBA {
case class A(value: Int)
case class B(value: Option[A])
case class C(value: B)
case class D(value: Option[C])
case class E(value: D)
val edcba: Option[E] = Some(E(D(Some(C(B(Some(A(1))))))))
val ednon: Option[E] = Some(E(D(None)))
}
import monocle.syntax._
import monocle.std.option._
import monocle.macros.GenLens
object Example1 {
import EDCBA._
val _a = GenLens[A](_.value)
val _b = GenLens[B](_.value)
val _c = GenLens[C](_.value)
val _d = GenLens[D](_.value)
val _e = GenLens[E](_.value)
def getAValue(edcba: Option[E]): Option[Int] =
edcba &<-? some[E, E] ^|-> _e ^|-> _d ^<-? some ^|-> _c ^|-> _b ^<-? some ^|-> _a getOption
def good: Option[Int] =
getAValue(edcba)
def bad: Option[Int] =
getAValue(ednon)
}
import monocle.Prism
import monocle.syntax._
import monocle.std.option._
import monocle.macros.GenLens
object Example2 {
import EDCBA._
val _a = GenLens[A](_.value)
val _b = Prism[B, A](_.value)(a => B(Some(a)))
val _c = GenLens[C](_.value)
val _d = Prism[D, C](_.value)(c => D(Some(c)))
val _e = GenLens[E](_.value)
def getAValue(edcba: Option[E]) =
edcba &<-? some[E, E] ^|-> _e ^<-? _d ^|-> _c ^<-? _b ^|-> _a getOption
def good: Option[Int] =
getAValue(edcba)
def bad: Option[Int] =
getAValue(ednon)
}
scala> import EDCBA._, Example2._
import EDCBA._
import Example2._
scala> import monocle._, Monocle._
import monocle._
import Monocle._
scala> edcba &<-? some[E, E] ^|-> _e ^<-? _d ^|-> _c ^<-? _b ^|-> _a set 999
res1: Option[EDCBA.E] = Some(E(D(Some(C(B(Some(A(999))))))))
scala> edcba &<-? some[E, E] ^|-> _e ^<-? _d ^|-> _c ^<-? _b ^|-> _a modify(_ + 200)
res2: Option[EDCBA.E] = Some(E(D(Some(C(B(Some(A(201))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment