Last active
December 18, 2015 03:19
-
-
Save channingwalton/5717025 to your computer and use it in GitHub Desktop.
Partial Lens example
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
object PartialLensExample extends App { | |
import scalaz._ | |
import Lens._ | |
import PLens._ | |
case class Bar(blub: Option[String]) | |
case class Foo(bar: Option[Bar]) | |
// normal lenses for getting and setting values | |
val fooBarL: Foo @> Option[Bar] = lensg(foo ⇒ bar ⇒ foo.copy(bar = bar), _.bar) | |
val barBlubL: Bar @> Option[String] = lensg(bar ⇒ blub ⇒ bar.copy(blub = blub), _.blub) | |
// compose the above as 'Partial Lenses', >=> is just an alias for 'andThen' | |
val fooBarBlubL: Foo @?> String = fooBarL.partial >=> somePLens >=> barBlubL.partial >=> somePLens | |
// try it | |
val foo = Foo(Some(Bar(Some("Hi")))) | |
println(fooBarBlubL.get(foo)) // Some(Hi) | |
println(fooBarBlubL.set(foo, "Bye")) //Foo(Some(Bar(Some(Bye)))) | |
// this doesn't really work well | |
val fooNone = Foo(None) | |
println(fooBarBlubL.set(fooNone, "huh")) // None | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment