Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Forked from calvinlfer/statefactorial.scala
Created June 29, 2017 10:36
Show Gist options
  • Save rajeevprasanna/8ac7bb017b836a598a53751b9e3cdf52 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8ac7bb017b836a598a53751b9e3cdf52 to your computer and use it in GitHub Desktop.
Factorial using the State monad
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