Last active
November 28, 2016 23:14
-
-
Save drstevens/ff2517a018c319a34a19accea535472f to your computer and use it in GitHub Desktop.
Monocle Optional and Traverable
This file contains hidden or 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 monocle.function.Each | |
import monocle.macros.GenLens | |
import monocle.{Lens, Optional} | |
sealed trait Foo | |
object Foo { | |
// This is similar to scalaz.PLens | |
val _foo1Opt: Optional[Foo, Foo1] = Optional[Foo, Foo1] { | |
case f1: Foo1 => Some(f1) | |
case f2: Foo2 => None | |
}(f1 => { | |
case _: Foo1 => f1 | |
case s: Foo2 => s | |
}) | |
} | |
case class Foo1(i: Int) extends Foo | |
object Foo1 { | |
val _i: Lens[Foo1, Int] = GenLens[Foo1](_.i) | |
} | |
case class Foo2(j: String) extends Foo | |
case class Bar(foo: Foo) | |
object Bar { | |
val _foo: Lens[Bar, Foo] = GenLens[Bar](_.foo) | |
} | |
val f1Partial = | |
Bar._foo.asOptional.composeOptional(Foo._foo1Opt.composeLens(Foo1._i)) | |
val b0 = List(Bar(Foo1(10)), Bar(Foo2("11")), Bar(Foo1(12))) | |
// set all the Foo1s to 100 | |
println(b0.map(f1Partial.set(100))) | |
case class ListBar(bars: List[Bar]) | |
object ListBar { | |
val _bars: Lens[ListBar, List[Bar]] = GenLens[ListBar](_.bars) | |
} | |
// What happens if it's wrapped in some other type? | |
// Provides Each[List[A], A] | |
import monocle.std.list._ | |
val f1Traversal = | |
ListBar._bars.composeTraversal( | |
Each.each[List[Bar], Bar].composeOptional(f1Partial)) | |
println(f1Traversal.set(100)(ListBar(b0))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment