在 Pyret 语言中,'shadow' 是做什么的?

In the language Pyret, what does 'shadow' do?

使用 Pyret,我找不到任何关于 shadow 的文档。这是我遇到的代码块:

fun parse(s :: S.S-Exp) -> ArithC:
  cases (S.S-Exp) s:
    | s-num(n) => numC(n)
    | s-list(shadow s) =>
      cases (List) s:
        | empty => raise("parse: unexpected empty list")
        | link(op, args) =>
          argL = L.index(args, 0)
          argR = L.index(args, 1)
          if op.s == "+":
            plusC(parse(argL), parse(argR))
          else if op.s == "*":
            multC(parse(argL), parse(argR))
          end
      end
    | else =>
      raise("parse: not number or list")
  end
end

我不熟悉这种语言,但隐藏通常是指拥有一个与可见外部范围中的变量同名的新变量。这可能会令人困惑。也许 'shadow' 是您用来允许隐藏的关键字?如果删除它,编译器是否会抱怨重新定义 's'?

从 Pyret 中的阴影文档中可以找到 here

Pyret does not permit a program to implicitly bind the same name multiple times in the same scope, as this can be confusing or ambiguous: which name was meant?

  ans = 3 + 4

  ans = true # did you mean to use a different name here?
  ans # which one was meant?

Pyret will signal an error on the second binding of ans above, saying that it shadows the earlier definition. The same rule applies to names defined in nested scopes, like functions. This program is disallowed by the shadowing rule, as well:

  ans = 3 + 4

  fun oops(x):
    ans = x * 2  # Shadows the outer ans
    ans
  end

  fun another-oops(ans): # Also shadows the outer ans
    if ans: 3 else: 4 end
  end

The general rule for shadowing is to look "upward and leftward", i.e. looking outward from the current scope to any enclosing scopes, to see if there are any existing bindings of the same name.

But sometimes, redefining the same name makes the most sense. In this case, a program can explicitly specify that it means to hide the outer definition, using the shadow keyword:

  ans = 3 + 4
  fun oops(x):
    shadow ans = x * 2 # <-------------------------+
    ans    # uses the ans defined the line above --+
  end
  fun another-oops(shadow ans):
    if ans: 3 else: 3 end # uses the function's parameter
  end