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

Derive Show with field labels #340

Merged
merged 4 commits into from
May 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions core/src/main/scala-3.0.0-RC3/cats/derived/all.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ object all extends
OrderDerivation,
PartialOrderDerivation,
SemigroupDerivation,
ShowDerivation,
TraverseDerivation
32 changes: 32 additions & 0 deletions core/src/main/scala-3.0.0-RC3/cats/derived/show.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package cats.derived

import cats.Show
import shapeless3.deriving.{Continue, K0, Labelling}

object show extends ShowDerivation

trait ShowDerivation:

extension (F: Show.type)
inline def derived[A](using gen: K0.Generic[A]): Show[A] = gen.derive(productShow, coproductShow)

given productShow[A](using inst : => K0.ProductInstances[Show, A], l: Labelling[A]): Show[A] =
(a: A) => {
var idx = 0
val x = inst.foldLeft[StringBuilder](a)(new StringBuilder(s"${l.label}("))(
[t] => (acc: StringBuilder, sh: Show[t], t0: t) => {
//elemLabels is backed by an array so this should be fast
val res = Continue(acc.append(s"${l.elemLabels(idx)}=${sh.show(t0)}, "))
idx = idx + 1
res
}
)
if(idx > 0) {x.delete(x.length - 2, x.length)}
x.append(")")
x.toString()
}

given coproductShow[A](using inst: => K0.CoproductInstances[Show, A]): Show[A] =
(a: A) => inst.fold[String](a)(
[t] => (sh: Show[t], t0: t) => sh.show(t0)
)
9 changes: 9 additions & 0 deletions core/src/test/scala-3.0.0-RC3/cats/derived/ShowTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package cats.derived

import alleycats._
import cats._
import cats.derived.all._

class ShowTests { //
case class Foo(i: Int, b: Option[String]) derives Show
}