Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. import cats.effect.IO
  2. import cats.effect.concurrent.Ref
  3. import cats.data.State
  4.  
  5. import scala.util.Random
  6.  
  7. object Awesome extends App {
  8.  
  9. case class Output(last: Option[String], count: Int)
  10. case class MyState(strings: List[String])
  11. object MyState {
  12. def init: MyState = MyState(List.empty[String])
  13. }
  14.  
  15. val ref = Ref.of[IO, MyState](MyState.init).unsafeRunSync()
  16.  
  17. def addWord(word: String): State[MyState, Output] = State[MyState, Output] { s =>
  18. s.copy(strings = s.strings :+ word) -> Output(s.strings.lastOption, s.strings.size)
  19. }
  20.  
  21. def program: IO[Unit] =
  22. for {
  23. str <- IO(Random.nextString(10))
  24. out <- ref.modifyState(addWord(str))
  25. st <- ref.get
  26. _ <- IO(println(s"Current Output $out"))
  27. _ <- IO(println(s"State $st"))
  28. _ <- program
  29. } yield ()
  30.  
  31. program.unsafeRunSync()
  32.  
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement