Snažím sa o prvý raz.
Tu je trieda prípadov:
case class State(mem: Map[String, Int], pointer: Int)
A súčasná úprava, používajúca štandardnú scala, ktorú by som rád robil:
def add1 = (s: State) => s.copy(
mem = s.mem.updated("a", s.mem("a") + 1),
pointer = s.pointer + 1
)
A tu je moja implementácia s monoklom
val mem = GenLens[State](_.mem)
val pointer = GenLens[State](_.pointer)
val add2 = (mem composeLens at("a")).modify(_.map(_ + 1)) andThen pointer.modify(_ + 1)
Kód však nie je čistejší…
- Existuje stručnejší spôsob?
- Môžeme generovať všetky kotlové tabuľky s makrami?
[update] Prišiel som s kombinátorom
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))
}
Problém je v tom, že stále musím vyrábať sprostredkovateľa a zbytočného S.
[update2] Vyčistil som kód pre kombinátor.
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)) }
}
odpovede:
2 pre odpoveď č. 1Pomocou programu môžete získať o niečo kratšiu verziu index
namiesto at
:
(mem composeOptional index("a")).modify(_ + 1) andThen pointer.modify(_ + 1)
Avšak, mergeLens
tiež známe ako horizontálne zloženie nespĺňa. \ t Lens
zákon Lenses
ukazujú na to isté pole:
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)