Skip to content

@jrwest /lenses-1-1.scala
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
// 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)
}
@nicerobot

lenses-1-8.scala:

val condition: Lens[Toy, ToyCondition] = Lens(_.condition, (t,c) => t copy (condition = c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.