public
Last active

  • Download Gist
lenses-1-1.scala
Scala
1 2 3 4 5
// 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)
// ...
}
lenses-1-10.scala
Scala
1 2
// 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)))
lenses-1-2.scala
Scala
1 2 3 4 5 6
// 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)
lenses-1-3.scala
Scala
1
case class ToyBox(toys: Map[String, Toy])
lenses-1-4.scala
Scala
1 2 3 4 5 6
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)
lenses-1-5.scala
Scala
1
def updateCondition(toyBox: ToyBox, name: String, newCondition: ToyCondition): ToyBox
lenses-1-6.scala
Scala
1 2 3 4 5
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)
}
lenses-1-7.scala
Scala
1
val toys: Lens[ToyBox, Map[String, Toy]] = Lens(_.toys, (tb,ts) => tb copy (toys = ts))
lenses-1-8.scala
Scala
1
val condition: Lens[Toy, Condition] = Lens(_.condition, (t,c) => t copy (condition = c))
lenses-1-9.scala
Scala
1 2 3 4 5
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)
}

lenses-1-8.scala:

val condition: Lens[Toy, ToyCondition] = Lens(_.condition, (t,c) => t copy (condition = c))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.