所以我最近读了下面这篇令人震惊的帖子:http://www.chuusai.com/2011/06/09/scala-union-types-curry-howard/
我真的很欣赏这种方法!我在试着做一个函数
def neq[A,B] = ...其中,neqString,String不能编译,但neqString,Int可以。这看起来应该是可能的,但我不认为我对使用curry-howard在类型中编码逻辑的方式有足够深入的理解。
我失败的尝试如下:
我认为我们想要的本质上是Xor。所以我们想要
A and ~B or ~A and B因为我们在scala中做隐式解析的时候都是像<:<,=:=这样的东西,我想我需要一个隐含在那里,因为那是<:<。所以我们说:
~(A and ~B) => (~A and B)但是,如果我尝试执行以下操作,这将不起作用:
implicitly[((String with (Int => Nothing)) => Nothing) <:< ((String => Nothing) with Int)]这是有道理的,因为类型根本不匹配。所以我真的不知道该去哪里!会很乐意得到任何指导。
发布于 2014-07-11 15:29:57
据我所知,你需要保证A和B的不等式(如果我错了,请纠正我)
Shapeless库中的好解决方案(来自Miles Sabin):
// Type inequalities
trait =:!=[A, B]
def unexpected : Nothing = sys.error("Unexpected invocation")
implicit def neq[A, B] : A =:!= B = new =:!=[A, B] {}
implicit def neqAmbig1[A] : A =:!= A = unexpected
implicit def neqAmbig2[A] : A =:!= A = unexpected您的neq方法将如下所示:
def neq[A,B](implicit ev : A =:!= B) = ...更新:
xor:
A and ~B or ~A and B按隐式解析不是:
~(A and ~B) <:< (~A and B)正确的转换是:
(A and ~B) <:!< (~A and B)
or:
(A and ~B) =:!= (~A and B)而不是scala代码:
type xor[A, B] = (A with ![B]) =:!= (![A] with B)
def neq[A,B](implicit ev : A xor B) = ...和测试:
neq[Int, String] // - ok
neq[String, Int] // - ok
//neq[String, String] // - compilation error
//neq[Int, Int] // - compilation error毕竟,它可以简化为:
A =:!= Bhttps://stackoverflow.com/questions/24691736
复制相似问题