2014-06-20 5 views
3

에 튜플 typeclasses를 구성 나는 typeclasses를 작성하고 상용구 코드를 방지하기 위해 추상화를 찾고 있어요? 어쩌면 엉망이 되겠지?스칼라

답변

5

네는 볼품은 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)] = [email protected] 

scala> implicitly[MyTypeClass[(Int, Int, Int)]] 
res1: MyTypeClass[(Int, Int, Int)] = [email protected] 

이 몇 가지 추가 논의를 위해 내 블로그 게시물 here를 참조하십시오.