-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
137: Practice Exercise: Building a Simple Interpreter with Pattern Matching
We've spent the last few lessons talking about the theory of pattern matching and algebraic data types, but it's one thing to read about it and another to actually use it to structure a program. To get this to stick, I want us to build a tiny interpreter. We aren't building a full-blown language—just a basic expression evaluator that can handle numbers, addition, multiplication, and variables.
Defining our Expression Language
Whenever I'm building an interpreter, I start by defining the "shape" of the data. In Scala, the gold standard for this is a sealed trait. By marking it sealed, I'm telling the compiler that all possible subtypes are defined in this file. This is huge because if I miss a case in my pattern match later, the compiler will actually yell at me.
sealed trait Expr
case class Num(value: Int) extends Expr
case class Add(left: Expr, right: Expr) extends Expr
case class Mul(left: Expr, right: Expr) extends Expr
case class Var(name: String) extends Expr
I've chosen these four because they cover the basics: a leaf node (Num), recursive nodes (Add and Mul), and a placeholder (Var). This creates a tree structure, which is exactly how most compilers represent code internally.
Writing the Evaluation Logic
Now we need a way to turn these Expr objects into an actual integer result. This is where the pattern matching magic happens. I'll write a function that recursively walks down the tree until it hits a number.
def eval(expr: Expr): Int = expr match {
case Num(n) => n
case Add(l, r) => eval(l) + eval(r)
case Mul(l, r) => eval(l) * eval(r)
case Var(name) => 0 // Wait, this is wrong.
}
Fixing the "Missing Context" Bug
I just caught myself making a classic mistake. I defined Var in my data model, but in my eval function, I just returned 0 because I didn't have any way to know what the variable was actually worth. A variable isn't a constant; it needs a context (or an environment).
I can't just hardcode values inside the function. I need to pass a map of variable names to values into the eval function. Let's rewrite the signature to fix this.
def eval(expr: Expr, env: Map[String, Int]): Int = expr match {
case Num(n) => n
case Add(l, r) => eval(l, env) + eval(r, env)
case Mul(l, r) => eval(l, env) * eval(r, env)
case Var(name) => env.getOrElse(name, throw new Exception(s"Variable $name not found!"))
}
Now the logic is sound. If the interpreter hits a Var, it looks it up in the env map. If it's not there, it throws an exception. It's simple, but it's the core loop of almost every interpreted language in existence.
Putting it all together
To see it in action, we just need to construct a tree and provide a context. Let's say we want to calculate (x + 5) * 2 where x is 10.
val expression = Mul(
Add(Var("x"), Num(5)),
Num(2)
)
val context = Map("x" -> 10)
val result = eval(expression, context)
println(result) // Output: 30
The beauty here is how clean the eval function remains. We don't have if/else chains or type casting. We just describe what the data looks like and what to do with it. If we wanted to add a Subtract or Divide case, we'd just add a case class to the trait and one line to the match block.
📋 Practical Task
Adding Subtraction and Power Operators to the Expression Evaluator
Now it's your turn to extend the interpreter. I've given you the base code, but it's missing a few common mathematical operations.
Your Task:
- Modify the
Exprtrait to include two new case classes:Sub(left: Expr, right: Expr)andPow(base: Expr, exponent: Expr). - Update the
evalfunction to handle these new cases. ForPow, you can usescala.math.pow(remember that it returns a Double, so you'll need to convert it back to an Int). - Create a test expression that represents
(10 - 2) ^ 2(which should result in 64) and evaluate it.
sealed trait Expr
case class Num(value: Int) extends Expr
case class Add(left: Expr, right: Expr) extends Expr
case class Mul(left: Expr, right: Expr) extends Expr
case class Var(name: String) extends Expr
// Add your new case classes here
def eval(expr: Expr, env: Map[String, Int]): Int = expr match {
case Num(n) => n
case Add(l, r) => eval(l, env) + eval(r, env)
case Mul(l, r) => eval(l, env) * eval(r, env)
case Var(name) => env.getOrElse(name, throw new Exception(s"Variable $name not found!"))
// Add your new match cases here
}There are no comments for now.