ATuin

Evaluate long computation only if needed

Apr 29th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.83 KB | None | 0 0
  1. scala> lazy val longComputation = IO{println("Long Computation ...."); 10.some}
  2. longComputation: scalaz.effect.IO[Option[Int]] = <lazy>
  3.  
  4. scala> lazy val shortComputation = IO{println("Short Computation ...."); 2.some}
  5. shortComputation: scalaz.effect.IO[Option[Int]] = <lazy>
  6.                                                                      
  7. scala> lazy val shortComputationFail:IO[Option[Int]] = IO{println("Short Computation ...."); none}
  8. shortComputationFail: scalaz.effect.IO[Option[Int]] = <lazy>
  9.  
  10. scala> (shortComputation >>= {o => o.isDefined? o.pure[IO] | longComputation}).unsafePerformIO
  11. Short Computation ....
  12. res49: Option[Int] = Some(2)
  13.  
  14. scala> (shortComputationFail >>= {o => o.isDefined? o.pure[IO] | longComputation}).unsafePerformIO
  15. Short Computation ....
  16. Long Computation ....
  17. res51: Option[Int] = Some(10)
Advertisement
Add Comment
Please, Sign In to add comment