Composing typeclasses for tuples in Scala

試著忘記壹切 提交于 2019-12-07 12:25:34

问题


I am looking for abstraction to compose typeclasses and avoid boilerplate code:

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
                               }
                }


}

Is there a boilerplate free approach ? Maybe in shapeless ?


回答1:


Yep, Shapeless can help you here, with its TypeClass type class:

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]

And then:

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

See my blog post here for some additional discussion.



来源:https://stackoverflow.com/questions/24321482/composing-typeclasses-for-tuples-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!