Created
May 5, 2022 06:12
-
-
Save yitonghe00/713a3b916ffd59ebbc6878367d5c8195 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
specialForms.set = (args, scope) => { | |
if (args.length !== 2 || args[0].type !== "word") { | |
throw new Error("Incorrect use of set."); | |
} | |
const value = evaluate(args[1], scope); | |
for(let outerScope = scope; scope; outerScope = Object.getPrototypeOf(outerScope)) { | |
if (Object.prototype.hasOwnProperty.call(outerScope, args[0].name)) { | |
// Found the binding at the level | |
outerScope[args[0].name] = value; | |
return value; | |
} | |
// Binding not found until the topScope | |
throw new ReferenceError("Binding not exist."); | |
}; | |
run(` | |
do(define(x, 4), | |
define(setx, fun(val, set(x, val))), | |
setx(50), | |
print(x)) | |
`); | |
// → 50 | |
run(`set(quux, true)`); | |
// → Some kind of ReferenceError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment