xuwei-k/scalaz-magnolia

Arbitrary

Closed this issue · 1 comments

to save you from writing one...

import magnolia._
import org.scalacheck._

import scalaz._, Scalaz._
import scalaz.scalacheck.ScalaCheckBinding._

object ScalacheckMagnolia {
  type Typeclass[A] = Arbitrary[A]

  def combine[A](ctx: CaseClass[Arbitrary, A]): Arbitrary[A] = Arbitrary {
    ctx.parameters.toList.traverse(p => Gen.lzy(p.typeclass.arbitrary)).map { ps =>
      ctx.rawConstruct(ps)
    }
  }

  def dispatch[A](ctx: SealedTrait[Arbitrary, A]): Arbitrary[A] = Arbitrary {
    Gen.frequency(ctx.subtypes.map(s => 1 -> (Gen.lzy(s.typeclass.arbitrary))): _*)
  }

  implicit def gen[A]: Arbitrary[A] = macro Magnolia.gen[A]

}

softwaremill/magnolia#118 (comment)

And there is also one for scalaz-deriving.

I'm going to be publishing this soon as part of

val derivingVersion = "<version>"
libraryDependencies ++= Seq(
  // the @deriving and @xderiving compiletime plugin and macro
  "com.fommil" %% "deriving-macro" % derivingVersion % "provided",
  compilerPlugin("com.fommil" %% "deriving-plugin" % derivingVersion),

  // the scalaz-deriving Altz / Decidablez / Deriving API and macros
  "com.fommil" %% "scalaz-deriving" % derivingVersion,

  // instances for Show and Arbitrary
  "com.fommil" %% "scalaz-deriving-magnolia" % derivingVersion,
  "com.fommil" %% "scalaz-deriving-scalacheck" % derivingVersion
)