Guest User

Untitled

a guest
Mar 23rd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. import cats.data.State
  2. import State._
  3.  
  4. def factorialWithState(x: Int): Int = {
  5. def stateFactorial: State[Int, Int] =
  6. // get accesses the State and places it in the User Value
  7. // in (State, User Value)
  8. get.flatMap(x =>
  9. // x is the User Value
  10. if (x <= 1)
  11. State.pure(1)
  12. else {
  13. // set the State in (State, User Value)
  14. set[Int](x - 1)
  15. .flatMap(_ =>
  16. // return a State that will compute the next iteration
  17. // stateFactorial's z is the User Value
  18. // what is the User Value? Look at stateFactorial
  19. // it calls get which access the State in (State, User Value)
  20. // and places that in User Value
  21. stateFactorial.map(z => x * z)
  22. )
  23. }
  24. )
  25. // return value in (State, Value)
  26. stateFactorial.run(x).value._2
  27. }
Add Comment
Please, Sign In to add comment