Skip to content

Instantly share code, notes, and snippets.

@channingwalton
Last active December 18, 2015 03:19
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 channingwalton/5717025 to your computer and use it in GitHub Desktop.
Save channingwalton/5717025 to your computer and use it in GitHub Desktop.
Partial Lens example
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