Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cats.data.State
- import State._
- def factorialWithState(x: Int): Int = {
- def stateFactorial: State[Int, Int] =
- // get accesses the State and places it in the User Value
- // in (State, User Value)
- get.flatMap(x =>
- // x is the User Value
- if (x <= 1)
- State.pure(1)
- else {
- // set the State in (State, User Value)
- set[Int](x - 1)
- .flatMap(_ =>
- // return a State that will compute the next iteration
- // stateFactorial's z is the User Value
- // what is the User Value? Look at stateFactorial
- // it calls get which access the State in (State, User Value)
- // and places that in User Value
- stateFactorial.map(z => x * z)
- )
- }
- )
- // return value in (State, Value)
- stateFactorial.run(x).value._2
- }
Add Comment
Please, Sign In to add comment