Fahad/CodeSamples/CaseClasses.scala
author Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
Sun, 09 Nov 2014 19:25:10 +0000
changeset 44 a751aa1ee4f7
permissions -rw-r--r--
Code Samples

package Main

abstract class Term
case class Var(name: String) extends Term
case class Fun(arg: String, body: Term) extends Term
case class Appli(f: Term, v: Term) extends Term

object TermTest extends App {
  def printTerm(term: Term) {
    term match {
      case Var(n) =>
        print("" + n)
      case Fun(x, b) =>
        print("^" + x + ".")
        printTerm(b)
      case Appli(f, v) =>
        Console.print("(")
        printTerm(f)
        print(" ")
        printTerm(v)
        print(")")
    }
  }
  def isIdentityFun(term: Term): Boolean = term match {
    case Fun(x, Var(y)) if x == y => true
    case _ => false
  }
  val id = Fun("x", Var("x"))
  println("id: " + id)
  val t = Fun("x", Fun("y", Appli(Var("x"), Var("y"))))
  println("t: " + t)
  printTerm(t)
  println
  println(isIdentityFun(id))
  println(isIdentityFun(t))
}