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 ofat
:However,
mergeLens
also known as horizontal composition does not satisfy theLens
law if the twoLenses
point to the same field: