Skip to content

Instantly share code, notes, and snippets.

@ismagin
Created June 28, 2017 12:31
Show Gist options
  • Save ismagin/0154c3a96828605f53bcc3f41a24220e to your computer and use it in GitHub Desktop.
Save ismagin/0154c3a96828605f53bcc3f41a24220e to your computer and use it in GitHub Desktop.
StateT and Gen
// resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
// libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0"
// libraryDependencies += "org.typelevel" %% "cats" % "0.9.0"
// libraryDependencies += "io.github.amrhassan" %% "scalacheck-cats" % "0.3.2" % Test
package ex
import cats._
import cats.data._
import cats.implicits._
import org.scalacheck.Gen
import org.scalacheck.support.cats._
import org.scalatest._
import org.scalatest.prop.GeneratorDrivenPropertyChecks
class ExampleSpec extends FlatSpec with Matchers with GeneratorDrivenPropertyChecks with SG {
case class InnerState(total: Int, floor: Int)
def step(i: InnerState): Gen[List[Int]] = {
if (i.floor == Int.MaxValue || i.total == 0) {
Gen.const(List.empty)
} else {
for {
head: Int <- Gen.choose(i.floor, Int.MaxValue)
tail <- step(InnerState(i.total - 1, head))
} yield head +: tail
}
}
def stepT: StateT[Gen, InnerState, List[Int]] = for {
i <- StateT.get[Gen, InnerState]
r <- if (i.floor == Int.MaxValue || i.total == 0) {
StateT.lift[Gen, InnerState, List[Int]](Gen.const(List.empty[Int]))
} else {
for {
nxt <- StateT.lift(Gen.choose(i.floor, Int.MaxValue))
_ <- StateT.set[Gen, InnerState](InnerState(i.total - 1, nxt))
tail <- stepT
} yield nxt +: tail
}
} yield r
def gen(amt: Int) = step(InnerState(amt, 0))
def genT(amt: Int) = stepT.runA(InnerState(amt, 0))
"plain" should "generate sorted array" in {
forAll(gen(10)) { l =>
println(l)
l.sorted shouldBe l
}
}
"transformed" should "generate sorted array" in {
forAll(genT(10)) { l =>
println(l)
l.sorted shouldBe l
}
forAll(stepT.runA(InnerState(10, Int.MaxValue - 5))) { l =>
println(l)
l.sorted shouldBe l
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment