【问题标题】:Equivalence of two types without consideing type parameters不考虑类型参数的两种类型的等价
【发布时间】:2015-01-08 17:35:41
【问题描述】:

我想要一些如下所示的隐含证据:

def foo[A, B](implicit ev: ???[A, B]) = ev

foo[Int, Int] //○ (compiles)
foo[Any, Int] //× (fails)
foo[Seq[Int], Seq[Int]] //○
foo[Seq[Any], Seq[Int]] //○
foo[Seq[Int], List[Int]] //×

所以两个类型必须属于同一个类,但是它们的类型参数无关紧要(就像ClassTag。)你如何实现这样的功能?你用宏吗?

谢谢!

【问题讨论】:

    标签: scala macros types implicit


    【解决方案1】:

    我的朋友在外面回答了 XD

    sealed trait ~[A, B]
    object ~ {
      implicit def a[A, B](implicit ev: A =:= B) = new ~[A, B] {}
      implicit def fa[F[_], A, B] = new ~[F[A], F[B]] {}
    }
    

    运行:

    scala> implicitly[Int ~ Int]
    res0: ~[Int,Int] = $tilde$$anon$1@574ae207
    
    scala> implicitly[Int ~ Any]
    <console>:10: error: could not find implicit value for parameter e: ~[Int,Any]
                  implicitly[Int ~ Any]
                            ^
    
    scala> implicitly[Seq[Int] ~ Seq[Any]]
    res2: ~[Seq[Int],Seq[Any]] = $tilde$$anon$2@27dc1857
    
    scala> implicitly[Seq[Int] ~ Seq[Int]]
    res3: ~[Seq[Int],Seq[Int]] = $tilde$$anon$2@69c33436
    
    scala> implicitly[Seq[Int] ~ List[Int]]
    <console>:10: error: could not find implicit value for parameter e: ~[Seq[Int],List[Int]]
                  implicitly[Seq[Int] ~ List[Int]]
                            ^
    

    【讨论】:

    • 太棒了!也应该为多个参数添加类型构造函数,def fab[F[_, _], A1, B1, A2, B2] = ....
    猜你喜欢
    • 2017-02-28
    • 2013-08-16
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 2014-02-26
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多