functional programming - Accessing Previous output while operator chaining in Scala -
how access resulting output value perform upcoming operation example:
scala> list(1,4,3,4,4,5,6,7) res0: list[int] = list(1, 4, 3, 4, 4, 5, 6, 7) scala> res0.removeduplicates.slice(0, ???.size -2)
in above line, need perform slice operation after removing duplicates. this, how access output of .removeduplicate()
, can use find size
slice operation.
i need perform in single step. not in multiple steps like:
scala> res0.removeduplicates res1: list[int] = list(1, 4, 3, 5, 6, 7) scala> res1.slice(0, res1.size -2) res2: list[int] = list(1, 4, 3, 5)
i want access intermediate results in final operation. removeduplicates()
example.
list.op1().op2().op3().finalop()
here want access: output of op1
,op2
,op3
in finalop
wrapping into option
may 1 option (no pun intended):
val finalresult = some(foo).map { foo => foo.op1(foo.stuff) }.map { foo => foo.op2(foo.stuff) }.map { foo => foo.op3(foo.stuff) }.get.finalop
you can make wrapping part implicit make little nicer:
object tapper { implicit class tapped[t] extends anyval(val v: t) { def tap[r](f: t => r) = f(v) } } import tapper._ val finalresult = foo .tap(f => f.op1(f.stuff)) .tap(f => f.op2(f.stuff)) .tap(f => f.finalop(f.stuff))
Comments
Post a Comment