Issue with reduce
Closed this issue · 1 comments
Maybe this doesn't work the way I'm expecting it to. It appears to me that the before is always an empty list. Am I doing something wrong?
Code:
val l = Var(ListString)
val before = l.reduce{(b,a) => println("before: "+b); b}
val after = l.reduce{(b,a) => println("after: "+a); a}
l() = l() :+ "9"
l() = l() :+ "2"
Results:
after: List(9)
before: List()
after: List(9,2)
before: List()
(Poking around at the state of things, and thought I'd chime in, since this doesn't seem to have received comments.)
This one's not surprising. The first time it runs, before receives ((), ("9")) and returns (). (Which is the value of b.) So when you change it again, it receives ((), "2"), prints () again, and returns ().
In other words, each instance of reduce receives the previous value from that reduce expression, and the new value of the Var. That's not necessarily intuitive, but it fits the usual meaning of reduce() in Scala collections; it's behaving as intended.
(I suspect you're thinking of something like a Fibonacci generator, where each run receives two adjacent values in the original list, but that's not what reduce does.)