Advertisement
EWTD

Higman and Kruskal relation

Jun 3rd, 2023
2,317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.34 KB | None | 0 0
  1. sealed trait Expr{ def HKRelation(expr: Expr): Boolean }
  2.  
  3. case class Variable(name: String) extends Expr {
  4.   override def toString: String = { name.toLowerCase() }
  5.   override def HKRelation(expr: Expr): Boolean = expr match {
  6.     case Variable(vname) => true
  7.     case Function(fname, fargs) => fargs.nonEmpty && fargs.exists(p => this.HKRelation(p))
  8.     case default => false
  9.   }
  10. }
  11.  
  12. case class Constant(name: String) extends Expr {
  13.   override def toString: String = { name.toUpperCase() }
  14.   override def HKRelation(expr: Expr): Boolean = expr match {
  15.     case Constant(cname) => name == cname
  16.     case Function(fname, fargs) => fargs.nonEmpty && fargs.exists(p => this.HKRelation(p))
  17.     case default => false
  18.   }
  19. }
  20.  
  21. case class Function(name: String, args: List[Expr] = List()) extends Expr {
  22.   override def toString: String = {
  23.     val args_str =
  24.       if (args.isEmpty)
  25.         "()"
  26.       else if (args.length == 1)
  27.         "(" + args.head.toString + ")"
  28.       else {
  29.         var buffer = args.head.toString
  30.         for(idx <- 1 until args.length) {
  31.           buffer += ", " + args.apply(idx).toString
  32.         }
  33.         "(" + buffer + ")"
  34.       }
  35.     name + args_str
  36.   }
  37.  
  38.   override def HKRelation(expr: Expr): Boolean = expr match {
  39.     case Function(fname, fargs) =>
  40.       fargs.nonEmpty && fargs.exists(p => this.HKRelation(p)) ||
  41.         (name == fname && args.length == fargs.length && args.iterator.zip(fargs.iterator).forall(x => x._1.HKRelation(x._2)))
  42.     case default => false
  43.   }
  44. }
  45.  
  46. object Main {
  47.   def main(args: Array[String]): Unit = {
  48.     val test1 = ( Function("Tree", Function("Leaf", Constant("A")::Nil) :: Function("Leaf", Variable("x") :: Nil) :: Nil),
  49.       Function("Tree", Function("Tree", Function("Leaf", Constant("A")::Nil) :: Function("Leaf", Function("f", Variable("y") :: Variable("z") :: Nil) :: Nil) :: Nil) ::
  50.                        Function("g", Variable("y") :: Variable("z") :: Nil) :: Nil))
  51.     val test2 =( Function("f", Function("g", Function("h", Variable("x") :: Nil) :: Nil) :: Nil),
  52.       Function("f", Function("h", Variable("x") :: Nil) :: Nil))
  53.     val tests = test1 :: test2 :: Nil
  54.     var testCnt = 1
  55.     for (test <- tests) {
  56.       println("Test #" + testCnt)
  57.       println(test._1.toString + " <= " + test._2.toString + " -> " + test._1.HKRelation(test._2))
  58.       testCnt += 1
  59.     }
  60.   }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement