我有一个不可变的数据结构,我在地图中有嵌套值,如下所示:
case class TradingDay(syms: Map[String, SymDay] = Map.empty)
case class SymDay(sym: String, traders: Map[String, TraderSymDay] = Map.empty)
case class TraderSymDay(trader: String, sym: String, trades: List[Trade] = Nil)
另外我有一天中所有交易的清单,我想生成TradingDay
结构,其中
case class Trade(sym: String, trader: String, qty: Int)
我试图通过折叠我的交易来弄清楚如何用镜头更新这个结构(见附录):
(TradingDay() /: trades) { (trd, d) =>
def sym = trd.sym
def trader = trd.trader
import TradingDay._
import SymDay._
import TraderSymDay._
val mod =
for {
_ <- (Syms member sym).mods(
_ orElse some(SymDay(sym)))
_ <- (Syms at sym andThen Traders member trader).mods(
_ orElse some(TraderSymDay(trader, sym)))
_ <- (Syms at sym andThen (Traders at trader) andThen Trades).mods(
trd :: _)
x <- init
} yield x
mod ! d
}
这有效;但是我想知道我是否可以减少重复性(在添加到地图然后修改地图键的值方面。它似乎没有比相关的深拷贝那么烦人。
附录 - 镜头
object TradingDay {
val Syms = Lens[TradingDay, Map[String, SymDay]](_.syms, (d, s) => d.copy(syms = s))
}
object SymDay {
val Traders = Lens[SymDay, Map[String, TraderSymDay]](_.traders, (d, t) => d.copy(traders = t))
}
object TraderSymDay {
val Trades = Lens[TraderSymDay, List[Trade]](_.trades, (d, f) => d.copy(trades = f))
}
答案 0 :(得分:6)
与
type @>[A,B] = Lens[A, B]
并保持这个镜头
val Syms : Lens[TradingDay, Map[String, SymDay]]
并定义这些镜头:
val F : Map[String, SymDay] @> Option[SymDay] = ...
val G : Option[SymDay] @> Map[String, TraderSymDay] = ...
val H : Map[String, TraderSymDay] @> Option[TraderSymDay] = ...
val I : Option[TraderSymDay] @> List[Trade] = ...
val J: TradingDay @> List[Trade] = Syms >=> F >=> G >=> H >=> I
你可以得到这个:
(trades /: TradingDay()){ (trd, d) => (J.map(trd :: _).flatMap(_ => init)) ! d }
答案 1 :(得分:0)
Jordan West提供的答案 (@_jrwest)
这只是一个小小的改变,涉及引入以下转换:
implicit def myMapLens[S,K,V] = MyMapLens[S,K,V](_)
case class MyMapLens[S,K,V](lens: Lens[S,Map[K,V]]) {
def putIfAbsent(k: K, v: => V)
= lens.mods(m => m get k map (_ => m) getOrElse (m + (k -> v)))
}
然后我们可以使用如下:
(TradingDay() /: trades) { (d, trade) =>
def sym = trade.sym
def trader = trade.trader
def traders = Syms at sym andThen Traders
def trades = Syms at sym andThen (Traders at trader) andThen Trades
val upd =
for {
_ <- Syms putIfAbsent (sym, SymDay(sym))
_ <- traders putIfAbsent (trader, TraderSymDay(trader, sym))
_ <- trades.mods(trade :: _)
} yield ()
upd ~> d
}