How to use monocle to modify a nested map and another field in scala

你说的曾经没有我的故事 提交于 2019-12-22 10:38:37

问题


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…

  1. Is there a more concise way ?
  2. 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)) }
  }

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!