Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Forked from calvinlfer/statefactorial.scala
Created June 29, 2017 10:35
Show Gist options
  • Save rajeevprasanna/b24e7e525d1b5e53fe1a5c5d36f755a5 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/b24e7e525d1b5e53fe1a5c5d36f755a5 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