Skip to content

Instantly share code, notes, and snippets.

@michaelahlers
Last active October 21, 2016 13:50
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 michaelahlers/20ec194410f89422847fdd3a71777c69 to your computer and use it in GitHub Desktop.
Save michaelahlers/20ec194410f89422847fdd3a71777c69 to your computer and use it in GitHub Desktop.
import scalaz.PLens._
import scalaz.Lens._
import scalaz._
case class Name(given: Option[String] = None, family: Option[String] = None)
val givenL: Name @> Option[String] = lensg(a => v => a.copy(given = v), _.given)
val familyL: Name @> Option[String] = lensg(a => v => a.copy(family = v), _.family)
case class Contact(name: Option[Name] = None)
val nameL: Contact @> Option[Name] = lensg(a => v => a.copy(name = v), _.name)
case class User(contact: Option[Contact] = None)
val contactL: User @> Option[Contact] = lensg(a => v => a.copy(contact = v), _.contact)
val contactNamePL: User @?> Option[Name] = ~contactL >=> somePLens >=> ~nameL
val nameGivenPL: User @?> Option[String] = contactNamePL >=> somePLens >=> ~givenL
val nameFamilyPL: User @?> Option[String] = contactNamePL >=> somePLens >=> ~familyL
val user = User()
val st =
for {
_ <- contactL %= { _ orElse Some(Contact()) }
_ <- contactNamePL %= { _ orElse Some(Name()) }
_ <- nameGivenPL := Some("Given")
_ <- nameFamilyPL := Some("Family")
} yield ()
val expected = User(Some(Contact(Some(Name(Some("Given"), Some("Family"))))))
val actual = st exec user
assert(actual == expected)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment