Advertisement
Guest User

Untitled

a guest
Nov 7th, 2014
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.55 KB | None | 0 0
  1.  
  2. sealed trait Type
  3. case object TypeRecHole extends Type
  4. case object IntType extends Type
  5. case object UnitType extends Type
  6. case class ProductType(types: Type*) extends Type
  7. case class LabeledType(ty: Type, label: String) extends Type
  8. case class TypeVar(name: String) extends Type
  9. case class MuType(param: String, ty: Type) extends Type
  10.  
  11. object SubtypeSum extends App {
  12.   def substRecTyVar(recParamName: String, ty: Type) = ty match {
  13.     case TypeVar(name) if name == recParamName => TypeRecHole
  14.     case
  15.   }
  16.   def geqType: (Type, Type) => Boolean = {
  17.     case (LabeledType(_, l1), LabeledType(_, l2)) => l1 >= l2
  18.     case (LabeledType(_, _), _) => true
  19.   }
  20.   def sub: (Type, Type) => Boolean = {
  21.     case (ProductType(ts1 @ _*), ProductType(ts2 @ _*)) =>
  22.       ts1.sortWith(geqType).zip(ts2.sortWith(geqType)).map(sub.tupled).reduce(_ && _)
  23.     case (LabeledType(ty1, l1), LabeledType(ty2, l2)) =>
  24.       if (l1 == l2) { assert(ty1 == ty2); true } else false
  25.     case (MuType(p1, ty1), MuType(p2, ty2)) =>
  26.       sub(substRecTyVar(p1, ty1), substRecTyVar(p2, ty2))
  27.     case (a, b) => a == b
  28.   }
  29.  
  30.   implicit class TypeOps(ty: Type) extends AnyRef {
  31.     def @@(label: String) = LabeledType(ty, label)
  32.   }
  33.  
  34.   val ty1 = MuType("X", ProductType( // μX.(nil|stop|cons Int X)
  35.     UnitType @@ "nil",
  36.     UnitType @@ "stop",
  37.     ProductType(IntType, TypeVar("X")) @@ "cons"
  38.   ))
  39.  
  40.   val ty2 = MuType("Y", ProductType( // μY.(nil|cons Int Y)
  41.     UnitType @@ "nil",
  42.     ProductType(IntType, TypeVar("Y")) @@ "cons"
  43.   ))
  44.  
  45.   println(sub(ty1, ty2))
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement