Advertisement
Guest User

Untitled

a guest
May 23rd, 2015
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. package nl.mdj.fpinscala
  2.  
  3. import akka.actor.Actor.Receive
  4. import akka.actor.{Props, Actor, ActorSystem, ActorRef}
  5. import akka.pattern.ask
  6. import akka.util.Timeout
  7. import nl.mdj.fpinscala.KeyValueStore.ListKeys
  8. import scala.concurrent.{Await, Future}
  9. import scala.concurrent.duration._
  10. import scalaz._
  11.  
  12.  
  13. object FreeActorMain extends App {
  14.  
  15. import scalaz.std.scalaFuture
  16.  
  17. val program = {
  18. for {
  19. _ <- KeyValueStore.put("value.1", "nee")
  20. _ <- KeyValueStore.put("value.2", "ja")
  21. keys <- KeyValueStore.listKeys
  22. value1 <- KeyValueStore.get(keys.head)
  23. exists <- KeyValueStore.exists(keys.head)
  24. } yield keys -> value1
  25. }
  26.  
  27.  
  28.  
  29. val system = ActorSystem()
  30. val actor = system.actorOf(KeyValueStore.props)
  31.  
  32. val nat = KeyValueStore.interperter(actor)(Timeout(2.second))
  33. val result = Free.runFC(program)(nat)(scalaFuture.futureInstance(scala.concurrent.ExecutionContext.global))
  34.  
  35. println(Await.result(result, 1.second))
  36. }
  37.  
  38. class KeyValueStore extends Actor {
  39. var map = Map.empty[String, Any]
  40.  
  41. override def receive: Receive = {
  42. case u:KeyValueStore.Get => sender ! map.get(u.key)
  43. case u:KeyValueStore.Exists => sender ! map.contains(u.key)
  44. case ListKeys => sender ! map.keys.toList
  45. case u:KeyValueStore.Put =>
  46. if(!map.contains(u.key)) {
  47. map += u.key -> u.value
  48. sender ! true
  49. } else {
  50. sender ! false
  51. }
  52.  
  53. }
  54. }
  55.  
  56. object KeyValueStore {
  57. sealed trait KeyValue[A]
  58. case class Put(key: String, value: String) extends KeyValue[Boolean]
  59. case class Exists(key: String) extends KeyValue[Boolean]
  60. case class Get(key: String) extends KeyValue[Option[String]]
  61. case object ListKeys extends KeyValue[List[String]]
  62.  
  63. type KvS[A] = Free.FreeC[KeyValue, A]
  64.  
  65. def put[A](key: String, value: String) = Free.liftFC(Put(key, value))
  66. def get[A](key: String) = Free.liftFC(Get(key))
  67. def exists[A](key: String) = Free.liftFC(Exists(key))
  68. def listKeys = Free.liftFC(ListKeys)
  69.  
  70. def props = Props(new KeyValueStore())
  71.  
  72. def interperter(actorRef: ActorRef)(implicit timeout: Timeout) = new (KeyValue ~> Future) {
  73. override def apply[A](fa: KeyValue[A]): Future[A] =
  74. actorRef.ask(fa).asInstanceOf[Future[A]]
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement