gpt4 book ai didi

scala - 在 Scala 中为元组编写类型类

转载 作者:行者123 更新时间:2023-12-01 11:38:42 24 4
gpt4 key购买 nike

我正在寻找抽象来组合类型类并避免样板代码:

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

查看我的博文 here进行一些额外的讨论。

关于scala - 在 Scala 中为元组编写类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24321482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com