kvalle/diy-lang

Question about scopes / environments

rcanepa opened this issue · 2 comments

First, I want to thank you for this amazing project. Right now, I am working on part 8 and I can tell you that I have learnt and enjoyed the process a lot.

I am not sure if this is the right place to ask for help (I could't find any information about where help question should be asked).

Anyway, I am looking for guidance on how should I approach this situation:

def test_let_bindings_overshadow_outer_environment():
    """
    Let bindings should shadow definitions in from outer environments
    """

    interpret("(define foo 1)", env)

    program = """
        (let ((foo 2))
             foo)
    """

My evaluator function creates a new Environment every time it found a "let" special form, which is created by extending the one its belong to:

def eval_let(ast, env):
    let_env = env.extend({})

    bindings = ast[1]

    print bindings

    args = {}
    for b in bindings:
        key = b[0]
        val = evaluate(b[1], let_env)
        args[key] = val
        let_env.set(key, val)

    print args

    return evaluate(ast[2], let_env)

However, this only work if I allow override already defined variables in my Environment (this way I can use the set method to change the value of a variable), but this doesn't seem to be right way to do it because I can also define multiple times the same variable, which of course is wrong.

How should I implement this behaviour correctly?. I need to be able to read variables from the parent environment and at the same time, define a local variable without raising a duplicated definition error.

Thanks!!

I found a solution extending the environment instead of defining (with set) new values.

Hi! Good to hear that you figured it out. If you get stuck again, feel free to ask new questions here.

Part 8 is newer than the rest, and thus less tested (by other people than me). So, if you find anything lacking/confusing/strange, feel free to file an issue or send a pull request!

Oh, and by the way, there is a solution branch if you feel like having a peak afterwards or if you get stuck.