[英]Composing typeclasses for tuples in Scala
我正在尋找抽象來組成類型類並避免樣板代碼:
sealed trait MyTypeClass[T]{
def add(t:T, mystuff:Something)
}
object MyTypeClass {
implicit def tupled[A,B](implicit adder1: MyTypeClass [A],adder2: MyTypeClass [B]): MyTypeClass [(A,B)] = new MyTypeClass [(A, B)] {
override def add(t: (A, B), mystuff: Something): Unit = {
val (a,b) = t
adder1 add a
adder2 add b
}
}
}
有免費的樣板嗎? 也許在無形?
是的,Shapeless可以幫助你,它的TypeClass
類型:
trait Something
sealed trait MyTypeClass[A] { def add(a: A, mystuff: Something) }
import shapeless._
implicit object MyTypeClassTypeClass extends ProductTypeClass[MyTypeClass] {
def product[H, T <: HList](htc: MyTypeClass[H], ttc: MyTypeClass[T]) =
new MyTypeClass[H :: T] {
def add(a: H :: T, myStuff: Something): Unit = {
htc.add(a.head, myStuff)
ttc.add(a.tail, myStuff)
}
}
def emptyProduct = new MyTypeClass[HNil] {
def add(a: HNil, mystuff: Something): Unit = ()
}
def project[F, G](instance: => MyTypeClass[G], to: F => G, from: G => F) =
new MyTypeClass[F] {
def add(a: F, myStuff: Something): Unit = {
instance.add(to(a), myStuff)
}
}
}
object MyTypeClassHelper extends ProductTypeClassCompanion[MyTypeClass]
然后:
scala> implicit object IntMyTypeClass extends MyTypeClass[Int] {
| def add(a: Int, myStuff: Something): Unit = {
| println(s"Adding $a")
| }
| }
defined module IntMyTypeClass
scala> import MyTypeClassHelper.auto._
import MyTypeClassHelper.auto._
scala> implicitly[MyTypeClass[(Int, Int)]]
res0: MyTypeClass[(Int, Int)] = MyTypeClassTypeClass$$anon$3@18e713e0
scala> implicitly[MyTypeClass[(Int, Int, Int)]]
res1: MyTypeClass[(Int, Int, Int)] = MyTypeClassTypeClass$$anon$3@53c29556
請參見我的博客文章在這里的一些額外的討論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.