Part I — Foundations · Chapter 2 · Lesson 3 of 5 · 8 min read
Lesson 3: Operators, Expressions, Precedence, and Evaluation
Lesson level: Foundation
Purpose: Learn how PeaLang combines values into expressions, determines grouping, evaluates operators, and avoids unnecessary work through short-circuit logic.
Learning objectives
By the end of this lesson, you should be able to:
- distinguish expressions from statements;
- use arithmetic, comparison, equality, and logical operators;
- apply unary minus and logical negation;
- predict expression grouping from precedence;
- explain left associativity;
- override grouping with parentheses;
- reason about truthiness and short-circuit evaluation; and
- diagnose common operator and evaluation failures.
3.1 What an expression is
An expression is source code that evaluates to a value. Literals, variable reads, arithmetic, comparisons, logical combinations, collection literals, indexing, property access, and function calls are expressions.
42
quantity
quantity * unit_price
subtotal >= threshold
A statement performs a program action such as declaring a binding, assigning a target, printing a value, or selecting a control-flow branch. Statements often contain expressions.
3.2 Arithmetic operators
| Operator | Purpose | Example |
|---|---|---|
| + | Addition or supported value combination | 5 + 2 |
| - | Subtraction | 5 - 2 |
| * | Multiplication | 5 * 2 |
| / | Division | 5 / 2 |
| % | Remainder | 5 % 2 |
The runtime applies the underlying operation to the evaluated operands. Addition can also combine compatible values such as strings or lists. Incompatible operands produce a runtime error rather than an invented conversion.
Division by zero fails. Use validation or a conditional before dividing when the denominator can be zero.
3.3 Comparison operators
Comparisons produce boolean values:
<, <=, >, >=
service_impact >= 8
affected_users < 100
The operands must support the requested comparison. A clear program compares compatible domain values and avoids relying on accidental conversions.
3.4 Equality operators
Use == to test equality and != to test inequality:
customer_tier == "gold"
assigned_agent != null
Do not confuse equality with assignment. = writes to a target; == evaluates a comparison and returns true or false.
3.5 Unary operators
Unary operators apply to one operand. PeaLang supports unary minus and logical negation:
-amount
not security_relevant
!security_relevant
Unary minus negates a numeric value. Both not and ! negate truthiness. Unary operators bind more tightly than multiplication, addition, comparison, equality, and logical combination.
3.6 Logical operators
PeaLang uses the word operators and, or, and not. The exclamation mark is also accepted for unary negation.
security_relevant or service_impact >= 8
customer_tier == "gold" and service_impact >= 5
not archived
Logical operators evaluate truthiness, not only literal booleans. However, explicit boolean conditions are usually clearer in rules and validation code.
3.7 Precedence hierarchy
When parentheses do not force grouping, PeaLang uses this precedence from highest to lowest:
| Level | Operators or forms |
|---|---|
| 1 | Primary values and parenthesized expressions |
| 2 | Postfix calls, indexing, and property access |
| 3 | Unary -, not, ! |
| 4 | *, /, % |
| 5 | +, - |
| 6 | <, <=, >, >= |
| 7 | ==, != |
| 8 | and |
| 9 | or |
Higher-precedence expressions become operands of lower-precedence operators.
3.8 Worked precedence examples
2 + 3 * 4 groups as 2 + (3 * 4), so the result is 14.
10 - 6 / 2 groups as 10 - (6 / 2), so the result is 7.
subtotal >= 30 and customer_tier == "gold" evaluates the comparison and equality expressions before applying and.
not active or urgent negates active first, then evaluates or.
3.9 Left associativity
Binary operators at the same precedence level group from left to right.
20 - 5 - 3 groups as (20 - 5) - 3, producing 12 rather than 18.
24 / 4 * 2 groups as (24 / 4) * 2, producing 12.
Associativity matters most for subtraction, division, remainder, comparisons, and mixed operators at one level. Do not rely on a reader remembering subtle grouping when parentheses can make intent obvious.
3.10 Parentheses
Parentheses create a primary expression and override normal precedence:
(2 + 3) * 4
The parenthesized sum is evaluated first, producing 20.
Use parentheses when they change grouping and when they make a complex condition easier to review:
security_relevant or (customer_tier == "gold" and service_impact >= 5)
The parentheses are not required by precedence because and binds more tightly than or, but they document the intended policy grouping.
3.11 Truthiness
Conditions and logical operators convert values to truthiness. False, null, numeric zero, empty strings, and empty collections are false-like; nonzero numbers, nonempty strings, and nonempty collections are true-like.
Although truthiness is convenient, explicit comparisons can better express domain intent. Prefer affected_users > 0 over simply affected_users when the numeric threshold matters to the reader.
3.12 Short-circuit and
For left and right, PeaLang evaluates left first. If left is false-like, the right expression is skipped and the result is false. If left is true-like, the right expression is evaluated and returned.
denominator != 0 and numerator / denominator > 2
When denominator is zero, the division is skipped. This pattern can guard a later expression, but the guard must appear on the left.
3.13 Short-circuit or
For left or right, PeaLang evaluates left first. If left is true-like, it becomes the result and the right expression is skipped. If left is false-like, the right expression is evaluated and returned.
security_relevant or service_impact >= 8
If security_relevant is true, the impact comparison does not need to be evaluated.
3.14 Logical results are not always booleans
The and/or evaluation rules return operand values in some cases. or returns the truthy left value when it short-circuits; otherwise it returns the evaluated right value. and returns false when the left side is false-like; otherwise it returns the evaluated right value.
For policy decisions, use boolean-producing comparisons when a boolean result is expected. This avoids surprising downstream values.
3.15 Expression evaluation trace
Trace this expression with customer_tier = "gold", service_impact = 6, and security_relevant = false:
security_relevant or customer_tier == "gold" and service_impact >= 5
Evaluate security_relevant → false; therefore evaluate the right operand of or.
Evaluate customer_tier == "gold" → true; therefore evaluate the right operand of and.
Evaluate service_impact >= 5 → true.
Apply and to its evaluated operands → true.
Return the evaluated right operand of or → true.
Precedence determines grouping, not permission to evaluate operands out of order. Evaluate the left operand of each logical operator first; evaluate its right operand only when the short-circuit rule requires it.
3.16 Postfix expressions
Calls, indexing, and property access bind more tightly than unary and binary operators:
scores[0] + scores[1]
case.impact >= 8
std.string.upper(name) == "PEA"
The target, index, property, function, and arguments are evaluated as required. Missing properties, invalid indices, or calling a non-callable value produce runtime errors.
3.17 Common evaluation failures
| Failure | Likely cause |
|---|---|
| Division by zero | The denominator evaluated to zero. |
| Unsupported operand operation | The operator received incompatible values. |
| Undefined variable | An operand name could not be resolved. |
| Index error | The index is invalid for the target collection. |
| Property not found | The target lacks the requested property or key. |
| Value is not callable | Call syntax was applied to a non-function value. |
The reported location is commonly associated with the expression node or operator that failed. Reduce a complex expression into named intermediate results to identify which subexpression is responsible.
3.18 Common mistakes
- Confusing = and ==: assignment writes; equality compares.
- Ignoring precedence: multiplication groups before addition, and and groups before or.
- Assuming all logical results are booleans: and/or can return operand values.
- Placing a guard on the right: short-circuit protection must be evaluated before the risky expression.
- Overusing truthiness: explicit domain comparisons are often clearer.
- Comparing incompatible values: validate or normalize data before comparison.
- Writing dense expressions: introduce named intermediates when a reader must mentally parse too much.
- Using parentheses decoratively but inconsistently: use them to document meaningful grouping.
3.19 Guided practice
- Evaluate 2 + 3 * 4 and (2 + 3) * 4.
- Evaluate 20 - 5 - 3 and explain associativity.
- Parenthesize a or b and c according to default precedence.
- Rewrite numerator / denominator > 2 with a short-circuit zero guard.
- Explain the difference between not x == y and not (x == y) under the precedence rules.
- Predict whether the right side of true or missing_name is evaluated.
- Predict whether the right side of false and missing_name is evaluated.
- Split one complex policy expression into named boolean intermediates.
3.20 Expression-debugging workflow
- Parenthesize the expression to show its grouping.
- Begin at the outermost expression and evaluate operands in source order.
- At each and or or node, evaluate the left operand first.
- Apply the short-circuit rule before entering the right-hand subtree.
- Evaluate arithmetic, calls, indexing, and comparisons only in subtrees actually reached.
- Record each computed value, its type, and every skipped subtree.
- Compare the trace with actual output and side effects.
3.21 Hands-on lab: Build an expression workbench
Create expression_workbench.pea that declares sample numeric, string, boolean, list, and map values. Print labeled results for:
- each arithmetic operator;
- comparison and equality operators;
- unary minus and both negation forms;
- two expressions whose result changes with parentheses;
- a left-associative subtraction chain;
- an and expression and an or expression;
- a safe division guarded by short-circuit evaluation;
- list indexing and map property or key access; and
- a standard-library function call used inside a comparison.
Prepare a prediction table before running the file. Then create temporary variants for division by zero, incompatible operands, an invalid index, a missing property, and calling a non-callable value.
Deliverable: The valid source, prediction table, actual output, and a failure table explaining the failing subexpression and minimal correction for each variant.
3.22 Review questions
- What is the difference between an expression and a statement?
- Which operators share the multiplication precedence level?
- Why does 2 + 3 * 4 evaluate multiplication first?
- What does left associativity mean for 20 - 5 - 3?
- How do parentheses affect an expression tree?
- Which binds more tightly: equality, and, or or?
- What does truthiness mean?
- When does and skip its right operand?
- When does or skip its right operand?
- Why can logical operators return non-boolean values?
3.23 Applied challenge
Rewrite the Chapter 1 case-priority conditions as named boolean expressions such as is_security_case, has_high_impact, and meets_gold_rule. Preserve precedence explicitly with parentheses, document rule combinations, and demonstrate that the refactored program produces the same decisions for the existing test matrix.
Lesson summary
Expressions evaluate to values and are grouped by a defined precedence hierarchy. Postfix and unary forms bind tightly, arithmetic precedes comparison and equality, and logical and precedes or. Operators at the same binary level associate left to right, while parentheses make intended grouping explicit. Truthiness and short-circuit evaluation can prevent unnecessary or unsafe evaluation, but explicit boolean expressions usually communicate policy most clearly.
Lesson status: Approved.