14

我有一个不可变的数据结构,其中我在 Maps 中有嵌套值,如下所示:

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))
}
4

2 回答 2

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 }
于 2012-04-20T14:44:40.803 回答
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
}
于 2012-04-25T14:01:45.543 回答