Docsity

Homework Assignment 3 Solutions: Static and Dynamic Scoping, Expression Evaluation - Prof., Assignments of Programming Languages

Partial preview of the text

Download Homework Assignment 3 Solutions: Static and Dynamic Scoping, Expression Evaluation - Prof. and more Assignments Programming Languages in PDF only on Docsity!

Homework Assignment 3 Solutions

Problem 1 a) 9 4 2 3 b) main static: --- dynamic: --- B static: main dynamic: main R static: B dynamic: B R static: B dynamic: R R static: B dynamic: R A static: B dynamic: R c) Procedure A checks its static link for g, and retrieves it from the environment for B. B, however, also knows about g from checking its static link and retrieving it from the environment for main.

Problem 2 Static scoping: 1 1 2 2 Dynamic scoping: 1 1 2 1 The difference comes from fact that the procedure print_x doesnโ€™t take x as an argument, and thus uses the scoping rules to find it. In static scoping, it uses the global x, but with dynamic scoping it uses the local x in procedure second. Problem 3 E โ†’ E 1 E 2 op E.val = โ€˜( โ€˜ + E 1 .val + op.val + E 2 .val + โ€˜ )โ€™ E โ†’ id E.val = id.name op โ†’ + | - | * | / op.val = โ€˜ + โ€˜ | โ€˜ - โ€˜ | โ€˜ * โ€˜ | โ€˜ / โ€˜ e.c. E โ†’ E 1 E 2 op E.op = op.val E.val = if (op.val == โ€˜ + โ€˜ || โ€˜ - โ€˜) then if (E 2 .op == โ€˜ + โ€˜ || โ€˜ - โ€˜) then E 1 .val + op.val + โ€˜ ( โ€˜ + E 2 .val โ€˜ )โ€™ else E 2 .val + op.val + E 2 .val else if (E 1 .op == โ€˜ + โ€˜ || โ€˜ - โ€˜) then โ€˜( โ€˜ + E 1 .val + โ€˜ ) โ€˜ + op.val + โ€˜ ( โ€˜ + E 2 .val + โ€˜ )โ€™ else E 1 .val + op.val + โ€˜ ( โ€˜ + E 2 .val + โ€˜ )โ€™ E โ†’ id E.val = id.name op โ†’ + | - | * | / op.val = โ€˜ + โ€˜ | โ€˜ - โ€˜ | โ€˜ * โ€˜ | โ€˜ / โ€˜ Problem 4 a) E โ†’ E 1 + T if (E 1 .type == T.type) E.type = E 1 .type else E.type = โ€˜realโ€™ E โ†’ T E.type = T.type T โ†’ num. num T.type = โ€˜realโ€™ T โ†’ num T.type = โ€˜intโ€™