LARA

Printing Prefix Infix Postfix

Recall tree.scala for the while language

  • it contained pretty-printer for infix expressions

Pretty printer for prefix, infix, and postfix expressions:

sealed abstract class Expr
case class Var(varID: String) extends Expr
case class IntLiteral(value: Int) extends Expr
case class Plus(lhs: Expr, rhs: Expr) extends Expr
case class Times(lhs: Expr, rhs: Expr) extends Expr
 
sealed abstract class Token
case class ID(str : String) extends Token
case class Const(c : Int) extends Token
case class Add extends Token
case class Mul extends Token
 
object Printer {
  def prefix(e : Expr) : List[Token] = e match {
    case Var(id)        => List(ID(id))
    case IntLiteral(c)  => List(Const(c))
    case Plus(lhs,rhs)  => List(Add()) ::: prefix(lhs) ::: prefix(rhs)
    case Times(lhs,rhs) => List(Mul()) ::: prefix(lhs) ::: prefix(rhs)
  }
  def infix(e : Expr) : List[Token] = e match { // should emit parantheses!
    case Var(id) =>       List(ID(id))
    case IntLiteral(c) => List(Const(c))
    case Plus(lhs,rhs) => infix(lhs) ::: List(Add()) ::: infix(rhs)
    case Times(lhs,rhs) => infix(lhs) ::: List(Mul()) ::: infix(rhs)
  }
  def postfix(e : Expr) : List[Token] = e match {
    case Var(id)        => List(ID(id))
    case IntLiteral(c)  => List(Const(c))
    case Plus(lhs,rhs)  => postfix(lhs) ::: postfix(rhs) ::: List(Add())
    case Times(lhs,rhs) => postfix(lhs) ::: postfix(rhs) ::: List(Mul())
  }
}
object Test {
 
  def main(args : Array[String]) = {
    val t = Plus(Var("x"),Times(Var("y"),Var("z")))
    println("prefix:  " + Printer.prefix(t))
    println("infix:   " + Printer.infix(t))
    println("postfix: " + Printer.postfix(t))
  }
}

Output:

$ scala Test
prefix:  List(Add(), ID(x), Mul(), ID(y), ID(z))
infix:   List(ID(x), Add(), ID(y), Mul(), ID(z))
postfix: List(ID(x), ID(y), ID(z), Mul(), Add())