Created
April 9, 2023 13:24
-
-
Save mpilquist/c9cb4f7d11facf10f03779734edbf52c to your computer and use it in GitHub Desktop.
Example of twiddle lists that work on Scala 2 (via aliases to shapeless HLists) and Scala 3 (using built-in tuples)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package examples | |
import org.typelevel.twiddles._ | |
import cats.Applicative | |
object Example { | |
trait Json | |
trait Decoder[A] { | |
def decode(s: Json): Option[A] | |
} | |
object Decoder extends TwiddleOps { | |
implicit val applicative: Applicative[Decoder] = new Applicative[Decoder] { | |
def pure[A](a: A): Decoder[A] = _ => Some(a) | |
def ap[A, B](ff: Decoder[A => B])(fa: Decoder[A]): Decoder[B] = j => | |
for { | |
a <- fa.decode(j) | |
f <- ff.decode(j) | |
} yield f(a) | |
} | |
} | |
val int: Decoder[Int] = _ => ??? | |
val string: Decoder[String] = _ => ??? | |
case class Foo(x: Int, y: String) | |
val fooDecoder: Decoder[Foo] = (int *: string).as[Foo] | |
case class Bar(x: Int) | |
val barDecoder: Decoder[Bar] = int.as[Bar] | |
case class Baz(x: Foo, y: Bar) | |
val bazDecoder = (fooDecoder *: barDecoder).as[Baz] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment