Skip to content

Instantly share code, notes, and snippets.

@terjesb
Forked from jrwest/lenses-1-1.scala
Created March 6, 2012 18:36
Show Gist options
  • Save terjesb/1988071 to your computer and use it in GitHub Desktop.
Save terjesb/1988071 to your computer and use it in GitHub Desktop.
// https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Lens.scala
case class Lens[A,B](get: A => B, set: (A,B) => A) {
def apply(a: A) = get(a)
// ...
}
// https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Lens.scala
def mod(a:A, f: B => B) : A = set(a, f(get(a)))
// https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Lens.scala
val fst = Lens[(A,B),A](_._1, (ab,a) => (a,ab._2))
fst.get((1, 2)) // 1
fst(("a", 2)) // "a"
fst.set((1, 2), 3) // (3, 2)
case class ToyBox(toys: Map[String, Toy])
sealed trait ToyCondition
case object New extends ToyCondition // toy has just been bought or rarely played with
case object Used extends ToyCondition // toy has obviously been played with
case object Destroyed extends ToyCondition // teeth have really sunk in, its trash time
case class Toy(condition: ToyCondition, daysOld: Int)
def updateCondition(toyBox: ToyBox, name: String, newCondition: ToyCondition): ToyBox
def updateCondition(toyBox: ToyBox, name: String, newCondition: ToyCondition): ToyBox = {
toyBox.toys.get(name)
.map(t => toyBox.copy(toys = toyBox.toys + (name -> t.copy(condition = newCondition))))
.getOrElse(toyBox)
}
val toys: Lens[ToyBox, Map[String, Toy]] = Lens(_.toys, (tb,ts) => tb copy (toys = ts))
val condition: Lens[Toy, Condition] = Lens(_.condition, (t,c) => t copy (condition = c))
def updateCondition(toyBox: ToyBox, name: String, newCondition: ToyCondition): ToyBox = {
toyBox.toys.get(name)
.map(t => toys.set(toyBox, toyBox.toys + (name -> condition.set(t, newCondition)))
.getOrElse(toyBox)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment