scala - Delayed Execution of a series of operations -
i'm trying write class when call function defined in class, store in array of functions instead of executing right away, user calls exec()
execute it:
class testa(val a: int, newaction: option[arraybuffer[(int) => int]]) { val action: arraybuffer[(int) => int] = if (newaction.isempty) arraybuffer.empty[(int) => int] else newaction.get def add(b: int): testa = {action += (a => + b); new testa(a, some(action))} def exec(): int = { var result = 0 action.foreach(r => result += r.apply(a)) result } def this(a:int) = this(a, none) }
then test code:
"delayed action" should "delay action till ready" in { val test = new testa(3) val result = test.add(5).add(5) println(result.exec()) }
this gives me result of 16 because 3 passed in twice , got added twice. guess easy way me solve problem not pass in value second round, change val a: int
val a: option[int]
. helps doesn't solve real problem: letting second function know result of first execution.
does have better solution this?? or if pattern, can share tutorial of it?
just save result of action in 'result' variable (instatiate 'a') , use previous result input current iteration
def exec(): int = { var result = action.foreach(r => result = r.apply(result)) result }
or use more functional oriented solution same
def exec(): int = { action.foldleft(a)((r, f) => f.apply(r)) }
Comments
Post a Comment