我有以下类与任务(Scalaz):
case class Foo(priceHistory: Task[Vector[Double]], average: Task[Double])
average
任务在其计算中运行priceHistory
任务。我可以做什么,以便priceHistory
在运行两个任务时不会计算两次?
average
任务:
Task({
val prices = priceHistory.unsafePerformSync
prices.foldLeft(0)((acc, p) => acc + p) / prices.length
})
priceHistory
任务:
Task(retrieveData(ticker, from, to))
示例电话:
average.unsafePerformSync // Internally runs priceHistory task
priceHistory.unsafePerformSync // Shouldn't have to be re-run...
答案 0 :(得分:1)
将您的价格历史记录放入monad,然后在您运行任务时对其进行一次评估。
case class Foo(priceHistory: Vector[Double], average: Double)
val priceHistoryTask: Task[Vector[Double]] = ???
val fooTask: Task[Foo] = for {
prices ← priceHistoryTask
avg = prices.sum / prices.length
} yield Foo(prices, avg)