call(back)
Algorithms & Data StructuresmediumSign in to star problems

SnowCal Interpreter

SnowCal is a tiny language with one integer register X, which starts at 0. A program is a list of lines:

ADD y      X = X + y
MUL y      X = X * y
FUN name   start recording a function body (the lines until END are stored, not run)
END        stop recording
INV name   run the recorded body of name

Bodies hold only ADD and MUL lines and are not nested. A function may be invoked any number of times; defining a name again replaces the earlier body. Return X after the last line.

snowcal(["FUN f", "ADD 1", "MUL 2", "END", "INV f", "INV f"])  ->  6

Hints

Hint 1

Keep a map from function name to its list of recorded (op, argument) lines, and a pointer to the body currently being recorded — null when you are executing.

Hint 2

Executing a line is one function used in two places: the top level, and the loop that replays a body on INV.

Asked at