Week 5 of 125
Crafting Interpreters, chapters 9 and 10
Sign up or sign in to tick these off and give this week a due date.
-
Control flow: if/else, logical operators with short-circuiting, while loops, and for loops implemented by desugaring into while. Lox becomes Turing-complete.
Time About 4 hours this week
Why it matters
Desugaring (implementing a feature by rewriting it into simpler features) is a key compiler technique. Short-circuit evaluation shows up in every language.
How to approach it
After implementing for-loop desugaring, print the AST of a for loop to see the rewritten while loop.
Challenges
3 challenges at the end of the chapter.
Challenge 3 (add break) is the one to implement; it is a good exercise in parser state and in using an exception or flag to unwind. Challenges 1 and 2 are thought exercises. Do challenges that change Lox's behavior on a separate git branch. The cracked.guide check runs the official test suite for this chapter, and a challenge that changes semantics (new syntax, different errors) can make tests fail on main.
Traps
- The dangling else: make sure else binds to the nearest if.
- Logical operators must return the operand value, not a converted boolean.
-
Functions: call expressions, arity checks, native functions like clock(), function declarations, return statements (implemented with an exception), and closures that capture their defining environment.
Time About 7 hours this week
Why it matters
Functions and closures are the heart of most modern languages. Implementing them makes callbacks, higher-order functions and closures in JavaScript or Python fully transparent.
How to approach it
Implement, then write a counter-making function to test closures. Write a recursive Fibonacci and time it with clock() so you have a baseline to compare against clox later.
Challenges
3 challenges at the end of the chapter.
Challenge 2 (anonymous functions) is the best one to implement. Challenge 3 is a short validity puzzle about parameters and locals. Do challenges that change Lox's behavior on a separate git branch. The cracked.guide check runs the official test suite for this chapter, and a challenge that changes semantics (new syntax, different errors) can make tests fail on main.
Traps
- Using an exception for return is correct here; do not try to "fix" it with flags unless you understand the trade-off.
- Binding the closure to the global environment instead of the current one breaks closures.
-
NeetCode LeetCode: 2 NeetCode 150 problems
Two problems from the NeetCode 150, in order. One box for the pair.