Tiny Language With Let
program is an expression in a tiny language. An expression is one of:
- a whole number such as
7or-3; - a variable, written as a name of lowercase letters;
(add A B), the sum of the expressionsAandB;(mult A B), their product;(let x1 A1 x2 A2 ... B), which sets the variablex1to the value ofA1, thenx2to the value ofA2, and so on in that order, and has the value of the last expressionB.
A variable set by a let lasts until the closing bracket of that let. Inside it, it hides a variable of the same name from further out, and a later pair of the same let may use it or set it again. Words are separated by single spaces, and add, mult and let are never variable names.
Return the value of program. A variable is only ever used where it has been set.
Example 1
program "(let a 5 b (add a 1) (mult a b))"
returns 30
a is 5, then b is a + 1 = 6, and the result is 5 * 6.
Example 2
program "(let x 2 (add (let x 7 x) x))"
returns 9
Inside the inner let, x is 7. After its closing bracket x is 2 again, so the sum is 7 + 2.
Example 3
program "(add 1 -4)"
returns -3
1 + (-4) is -3.
Constraints
1 <= len(program) <= 200- every value along the way lies between
-109and109
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Stacks and queues problems
- Value of a Logic FormulaHard
- Close Every BracketBeginner
- Crate PileBeginner
- Dead-End DrivewayBeginner
- Elevator TripsBeginner
- Flip the PancakesBeginner
- Last In, First OutBeginner
- Notes on the BoardBeginner