Advertisement
jules0707

PatternMatching

Feb 27th, 2017
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.57 KB | None | 0 0
  1.     package example
  2.    
  3.     trait Expr
  4.     case class Number(n: Int) extends Expr
  5.     case class Sum(e1: Expr, e2: Expr) extends Expr
  6.     case class Var(x:Int) extends Expr
  7.     case class Prod(e1: Expr, e2: Expr) extends Expr
  8.    
  9.    
  10.     object week4PatternMatching {
  11.       def eval(e: Expr): Int = e match {
  12.         case Number(n)   => n
  13.         case Sum(e1, e2) => eval(e1) + eval(e2)
  14.        
  15.       }
  16.      
  17.       def show(e:Expr): String = e match{
  18.       case Number(n)=> "n"
  19.       case Sum(l,r) => show(l) + "+" + show(r)
  20.       case Prod(l,r)=> show(l) + "*" + show(l)
  21.       }
  22.      
  23.       show(Sum(Number(1),Number(44)))
  24.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement