沿this question線的最大常見的亞型,我試圖找到一種方式來獲得Scala編譯器來推斷兩種類型的最大常見的亞型A和B.找到兩個斯卡拉類型
喜歡的東西「A無B」,其中所述的定義是:
(A without B = C) === (A = C with B)
,或者不返回C,一個功能類型,其中:
編輯:
A <: C && C <:!< B
ie。 A是C的亞型,C不是B的亞型
事實上,我期望有人會指出,這是不一樣的「最大的共同亞型」,因爲我實際上並不需要A <: B
。
用法:
trait Syntax
trait ANYSYNTAX extends Syntax
trait NUMERIC extends ANYSYNTAX
trait DISCRETE extends ANYSYNTAX
trait POSITIVE extends ANYSYNTAX
trait CONST extends ANYSYNTAX
type NUMCONST = NUMERIC with CONST
type POSCONST = POSITIVE with CONST
type ORDINALCONST = DISCRETE with CONST
type INTEGER = NUMERIC with DISCRETE
type POSNUM = POSITIVE with NUMERIC
type POSINT = POSNUM with INTEGER
type INTCONST = INTEGER with NUMCONST with ORDINALCONST
type POSNUMCONST = POSNUM with POSCONST with NUMCONST
type POSINTCONST = POSNUMCONST with INTCONST with POSINT
然後我想是能夠傳播類型的限制,具體如下:
abstract class Expression[+R](val args: Expression[_]*)
case class Add[A <: R, R <: NUMERIC](arg1: Expression[A], arg2: Expression[A]) extends Expression[R] {
case class Subtract[A <: R, R : A without POSITIVE](arg1: Expression[A], arg2: Expression[A]) extends Expression[R] {
case class Multiply[A <: R, R <: NUMERIC](arg1: Expression[A], arg2: Expression[A]) extends Expression[R]{
case class Divide[A <: R, R : A without DISCRETE](arg1: Expression[A], arg2: Expression[A]) extends Expression[R] {
我一直在試圖拿出東西借來使用某種類型的約束從其他答案:
sealed class =!=[A,B]
trait LowerPriorityImplicits {
implicit def equal[A]: =!=[A, A] = sys.error("should not be called")
}
object =!= extends LowerPriorityImplicits {
implicit def nequal[A,B](implicit same: A =:= B = null): =!=[A,B] =
if (same != null) sys.error("should not be called explicitly with same type")
else new =!=[A,B]
}
// Encoding for "A is not a subtype of B"
trait <:!<[A, B]
// Uses ambiguity to rule out the cases we're trying to exclude
implicit def nsub[A, B] : A <:!< B = null
implicit def nsubAmbig1[A, B >: A] : A <:!< B = null
implicit def nsubAmbig2[A, B >: A] : A <:!< B = null
我有一些測試用例:
implicitly[POSINT <:!< CONST]
implicitly[POSITIVE <:!< OPINION]
implicitly[DOGMA <:!< CONST]
implicitly[POSINTCONST <:< POSITIVE with CONST]
implicitly[POSINTCONST <:< POSCONST]
implicitly[POSITIVE with CONST <:!< POSINTCONST]
implicitly[POSITIVE =:= POSCONST without CONST]
implicitly[NUMERIC =:= INTEGER without DISCRETE]
implicitly[POSINT =:= POSINTCONST without CONST]
這些應該失敗:
implicitly[POSINT =:= POSINTCONST without OPINION]
implicitly[POSINT with OPINION =!= POSINTCONST without OPINION]
我不確定我是否理解你的定義。聽起來好像是'A <:B',然後'C'不存在,否則'C'只是'A'。 –
@TravisBrown例如,'C:POSINT','B:CONST'。然後'A:C與B' = POSINTCONST。根據我的第一個定義,'沒有CONST的POSINTCONST =:= POSINT'。如果另一方面是'A <:! RealName
其實@Travis我在我的第二個定義中犯了一個錯誤(我希望現在修復了)。 – RealName