Last active
November 11, 2023 05:22
-
-
Save gigiigig/3cd104e8951b4432afd5 to your computer and use it in GitHub Desktop.
Aux Pattern
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
import shapeless._ | |
import scalaz._ | |
import Scalaz._ | |
object console extends App { | |
trait Foo[A] { | |
type B | |
def value: B | |
} | |
object Foo { | |
type Aux[A0, B0] = Foo[A0] { type B = B0 } | |
implicit def fi = new Foo[Int] { | |
type B = String | |
val value = "Foo" | |
} | |
implicit def fs = new Foo[String] { | |
type B = Boolean | |
val value = false | |
} | |
} | |
def ciao[T, R](t: T) | |
(implicit f: Foo.Aux[T, R], | |
m: Monoid[R]): R = f.value | |
val res = ciao(2) | |
println(s"res: ${res}") | |
} |
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
import scalaz._ | |
import Scalaz._ | |
object console extends App { | |
trait Apart[F]{ | |
type T | |
type W[X] | |
def apply(f: F): W[T] | |
} | |
object Apart { | |
def apply[F](implicit apart: Apart[F]) = apart | |
type Aux[FA, F[_], A] = Apart[FA]{ type T = A; type W[X] = F[X] } | |
implicit def mk[F[_], R]: Aux[F[R], F, R] = new Apart[F[R]]{ | |
type T = R | |
type W[X] = F[X] | |
def apply(f: F[R]): W[T] = f | |
} | |
} | |
def mapZero[Thing, F[_], A](thing: Thing) | |
(implicit apart: Apart.Aux[Thing, F, A], | |
f: Functor[F], | |
m: Monoid[A]): F[A] = | |
f.map(apart(thing))(_ => m.zero) | |
mapZero(Option(3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great example, thank you!