Intersection Types in Scala

I know that “union types” are not supported in Scala, but what about intersection types?

In short, I need a function like this:

def intersect[A,B,C](a: A, b: B): C = ??? // a & b

Or method:

class A {
    def intersect[B, C](b: B): C = ??? // this & b
}

Aand Buse a common superclass that ensures the validity of the intersection, but Cwill be a type at the intersection Aor B.

In my case, using A or B represents either variables or constants (of the same type). I want to distinguish, by class, the constant from a variable with a singleton domain. If I try to cross the set with a value, I return a value (or return an empty set / throw value if an exception is not in the set).

Here is an example of the expected output:

trait IntExpression {
  // Correct signature to be determined
  def intersect [A <: IntExpression, B <: A & this.type] (that: A): B
}
case class IntVariable(domain: Seq[Int]) extends IntExpression
case class IntConstant(value: Int) extends IntExpression

val a = IntVariable(1,2,3)
val b = IntVariable(2,3,4)
val c = IntConstant(2)

And then:

a intersect b == b intersect a == IntVariable(2,3)
a intersect c == c intersect a == IntConstant(2)
+4
2

, ziggystar: A & B A with B Scala.

, C , , , A B.

, , , ?.

, , - http://en.wikipedia.org/wiki/Dependent_type. , Scala, Agda;)

+2

++ , . intersect Set , Set . , .

def intersect[C, A <: C, B <: C](as: Seq[A], bs: Seq[B]): Seq[C] = as ++ bs
0

All Articles