Skip to content

Instantly share code, notes, and snippets.

@jrwest
Created February 9, 2012 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jrwest/1783990 to your computer and use it in GitHub Desktop.
Save jrwest/1783990 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)
}
@nicerobot
Copy link

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