-
-
Save rajeevprasanna/8ac7bb017b836a598a53751b9e3cdf52 to your computer and use it in GitHub Desktop.
Factorial using the State monad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cats.data.State | |
import cats.data.State._ | |
def factorialWithState(x: Int): Int = { | |
def stateFactorial: State[Int, Int] = | |
get.flatMap(x => | |
if (x <= 1) | |
State.pure(1) | |
else { | |
set[Int](x - 1).flatMap(_ => stateFactorial.map(z => x * z)) | |
} | |
) | |
// return value in (State, Value) | |
stateFactorial.run(x).value._2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment