SICP:1.1.2 Naming and the Environment
SICP:1.1.2 Naming and the Environment
本文逐段翻译 SICP 第二版 §1.1.2《Naming and the Environment》,保留 Scheme code、REPL 输入/输出、
define、environment 和原文脚注位置。
TL;DR
- Programming language 必须提供用 names 指向 computational objects 的方式。
- 在 Scheme 中,
define把 name 与 value 关联起来,是最简单的 abstraction mechanism。 - Interpreter 通过 environment 维护 name-object pairs,使 program 能够增量构造、测试和复用更复杂的 computational objects。
目录
| 章节 | 说明 |
|---|---|
| 1.1.2 Naming and the Environment | name、variable 与 value |
使用 define 命名 | Scheme 中的 name-object association |
| Environment | interpreter 的 memory |
1.1.2 Naming and the Environment
Programming language 的一个 critical aspect,是它提供了使用 names 指向 computational objects 的方式。我们说,一个 name identifies 一个 variable,而该 variable 的 value 就是这个 object。
在 Lisp 的 Scheme dialect 中,我们使用 define 为事物命名。输入:
(define size 2)
会使 interpreter 把 value 2 与 name size 关联起来1。一旦 name size 已经与 number 2 关联,我们就可以通过 name 引用 value 2:
size
2
(* 5 size)
10
下面是更多使用 define 的 examples:
(define pi 3.14159)
(define radius 10)
(* pi (* radius radius))
314.159
(define circumference (* 2 pi radius))
circumference
62.8318
define 是 language 最简单的 abstraction means,因为它允许我们使用 simple names 指向 compound operations 的 results,例如上面计算出的 circumference。
一般来说,computational objects 可能具有非常 complex 的 structures;每次想使用它们时,都必须记住并重复这些 details,会极其 inconvenient。事实上,complex programs 是通过逐步构造 complexity 不断增加的 computational objects 建立起来的。Interpreter 使这种 step-by-step program construction 特别 convenient,因为 name-object associations 可以在 successive interactions 中 incremental 地创建。这一 feature 鼓励 program 的 incremental development and testing,并且很大程度上解释了为什么一个 Lisp program 通常由大量相对 simple 的 procedures 构成。
Environment
显然,把 values 与 symbols 关联起来、之后又能检索它们,意味着 interpreter 必须维护某种 memory,用于跟踪 name-object pairs。这块 memory 称为 environment(更精确地说是 global environment,因为稍后我们会看到,一个 computation 可能涉及多个不同的 environments)2。
在后续章节中,environment 不只是一个保存 bindings 的抽象容器;它还会成为理解 procedure application、local names、internal definitions 和 evaluator 的关键模型。当前先记住:当 interpreter 读取一个 name 时,它需要在 environment 中找到该 name 对应的 object;当执行 define 时,它会在 environment 中建立或更新这种 association。
图与格式复核
- 本节原文没有独立图片或表格。
- Scheme REPL 输入/输出和
defineexamples 保留为 code blocks;没有把代码中的 identifiers 翻译成中文。 - 原文的 name → variable → value、incremental development/testing 和 global environment 的叙述顺序保持不变。
术语对照
| English | 译法/处理 |
|---|---|
| name | 保留 name;必要处译作名称 |
| variable / value | 保留 variable/value;必要处译作变量/值 |
| computational object | 保留 computational object;必要处译作计算对象 |
| association / binding | 保留 association;后文按语境使用 binding |
| define | 保留 Scheme special form 名称 |
| abstraction | 保留 abstraction;必要处译作抽象 |
| environment | 保留 environment;必要处译作环境 |
| global environment | 保留 global environment;必要处译作全局环境 |
| incremental development and testing | 保留完整术语;必要处译作增量开发与测试 |
参考资料
- Harold Abelson、Gerald Jay Sussman、Julie Sussman:SICP 第二版 MIT Press 页面
- SICP HTML full text
- MIT OCW 6.001 Readings
评论 (0)