Guest User

Untitled

a guest
Jul 18th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. import Responder._
  2.  
  3. import scalaz._
  4.  
  5. object ResponderDemo extends Application {
  6. import Scalaz._
  7.  
  8. // --------------------------------------------------------------------------
  9. // Uses Responder (a continuation monad) to compose asynchronous functions.
  10. // --------------------------------------------------------------------------
  11.  
  12. // asynchronously concat s1 and s2 and call k with result
  13. def concat(s1: String, s2: String, k: String => Unit): Unit = new Thread() {
  14. override def run {
  15. Thread sleep 1000
  16. k(s1 + s2)
  17. }
  18. }.start
  19.  
  20. // concrete responder passing a concatenation result to continuation k
  21. class ConcatResponder(s1: String, s2: String) extends Responder[String] {
  22. def respond(k: (String) => Unit) = concat(s1, s2, s => k(s))
  23. }
  24.  
  25. // Creates a Kleisli instance that appends s2 when applied to input String s1
  26. def append(s2: String, f: String => String = s => s): Kleisli[Responder, String, String] =
  27. kleisli((s1: String) => new ConcatResponder(s1, s2).map(f))
  28.  
  29. // Kleisli composition of asynchronous functions
  30. val c1 = append("b") >=> append("c") >=> append("d") >=> append("e")
  31.  
  32. // ... or usage in a for-comprehension
  33. def c2(s: String) = for {
  34. s1 <- append("x")(s)
  35. s2 <- append("y")(s1)
  36. s3 <- append("z")(s2)
  37. } yield s3
  38.  
  39. // applications of c1 and c2 run concurrently
  40. c1("a") respond println // prints "abcde" after approx. 4 seconds
  41. c2("a") respond println // prints "axyz" after approx. 3 seconds
  42. }
Add Comment
Please, Sign In to add comment