I'm giving a try to monocle for the first time.
Here is the case class :
case class State(mem: Map[String, Int], pointer: Int)
And the current modification, using standard scala, that I would like to do :
def add1 = (s: State) => s.copy(
mem = s.mem.updated("a", s.mem("a") + 1),
pointer = s.pointer + 1
)
And here is my implementation with monocle
val mem = GenLens[State](_.mem)
val pointer = GenLens[State](_.pointer)
val add2 = (mem composeLens at("a")).modify(_.map(_ + 1)) andThen pointer.modify(_ + 1)
Unfortunately, the code is not cleaner…
- Is there a more concise way ?
- Can we generate all the boilerplate with macros ?
[update] I've come up with a combinator
def combine[S, A, B](lsa : Lens[S, A], f: A => A, lsb: Lens[S, B], g: B => B) : S => S = { s =>
val a = lsa.get(s)
val b = lsb.get(s)
val s2 = lsa.set(f(a))
val s3 = lsb.set(g(b))
s2(s3(s))
}
The problem is that I still need to produce an intermediary and useless S.
[update2] I've cleaned up the code for the combinator.
def mergeLens[S, A, B](lsa : Lens[S, A], lsb : Lens[S, B]) : Lens[S, (A, B)] =
Lens.apply[S, (A, B)](s => (lsa.get(s), lsb.get(s)))(t => (lsa.set(t._1) andThen lsb.set(t._2)))
def combine[S, A, B](lsa : Lens[S, A], f: A => A, lsb: Lens[S, B], g: B => B) : S => S = {
mergeLens(lsa, lsb).modify { case (a, b) => (f(a), g(b)) }
}
You can get a slightly shorter version using index
instead of at
:
(mem composeOptional index("a")).modify(_ + 1) andThen pointer.modify(_ + 1)
However, mergeLens
also known as horizontal composition does not satisfy the Lens
law if the two Lenses
point to the same field:
import monocle.macros.GenLens
case class Person(name: String, age: Int)
val age = GenLens[Person](_.age)
val age2 = mergeLens(age, age)
val john = Person("John", 25)
age2.get(age2.set((5, 10))(john)) != (5, 10)
来源:https://stackoverflow.com/questions/41410854/how-to-use-monocle-to-modify-a-nested-map-and-another-field-in-scala