Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typeclass Different from the Derived type #510

Open
agaro1121 opened this issue Jan 12, 2024 · 0 comments
Open

Typeclass Different from the Derived type #510

agaro1121 opened this issue Jan 12, 2024 · 0 comments

Comments

@agaro1121
Copy link

agaro1121 commented Jan 12, 2024

This question is for Scala3

Is there any way for the Typeclass to be different than the derived type?

For example:

trait Thing[A]
trait OtherThing[A]

object Thing extends Derivation[???] {
  type Typeclass[A] = OtherThing[A]

   override def join[T](caseClass: CaseClass[OtherThing, T]): Thing[T] = ???
   override def split[T](sealedTrait: SealedTrait[OtherThing, T]): Thing[T] = ???
}

// usage

Thing.derive[SomeA]

We do something similar to this in Scala 2 to generate an Gen[List[A]] that holds exactly one instance of an arbitrary for every sub type in a sealed trait. This is extremely useful for testing.

Here's the implementation that works in Scala 2:

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

  def join[A](ctx: CaseClass[Arbitrary, A]): Gen[List[A]] =
    ctx
      .constructMonadic(p => Gen.lzy(p.typeclass))
      .map(a => List(a))

  def split[A](ctx: SealedTrait[Arbitrary, A]): Gen[List[A]] =
    ctx.subtypes.toList
      .foldLeft(Gen.const(List.empty[A])) { (acc, next) =>
        acc.flatMap { xs => Gen.lzy(next.typeclass.arbitrary).map(_ :: xs) }
      }

  def gen[A]: Gen[List[A]] = macro Magnolia.gen[A]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant