TLS 02 Do it, Do it Again, and Again, and Again...
[The Little Schemer] 02 Do it, Do it Again, and Again, and Again…
About condition, loop and recursive.
Question-01: 判断列表 l 中的所有 S-expression 是否都是 atom
Question-02: 判断 S-expression 'a' 是否是列表 l 中的一个 S-expression
示例程序
lat?
1 | (define lat? |
1 | (lat? (quote (a b c))) |
member?
1 | (define member? |
1 | (display (member? (quote c) (quote (a b c)))) |
Lat? 函数分析
Cond 条件表达式
1 | (cond |
\(p_i\) 表示 Propositional Expression(命题表达式),其值为布尔值;\(e_i\) 表示 Expression(表达式)。
else总是为 \(T\)。
a conditional expression has the form: \[ (p_1\to e_1,\cdots,p_n\to e_n) \] 从左到右依次检查 \(p_i\)。如果 \(p_k\) 为 \(T\) 且 \(\forall j < k:p_j\ \text{is not undefined}\),则条件表达式的值为对应的 \(e_k\) 的值。如果 \(p_k\) 为 \(T\) 且 \(\exist j < k:p_j\ \text{is undefined}\),或 \(\forall i: p_i=F\),则条件表达式的值为 \(\text{undefined}\)。 例如: \[ (2 < 1\to 4,2 > 1\to 3)=3 \] \[ (2 < 1\to 3,2 > 1\to\frac{0}{0})\ \text{is undefined} \] \[ (2 < 1\to 3,4 < 1\to 4)\ \text{is undefined} \] \[ (\frac{0}{0}==0\to 1, 2 > 1\to 2)\ \text{is undefined} \]
第一个问题
询问 l 是否为 NULL,是则返回 #t 的值,否则询问下一个问题。
1 | ((null? l) #t) |
第二个问题
询问 l 的第一个 S-expression 是否为 atom,是则执行 (lat? (cdr l)),即调用 lat? 函数对 (cdr l) 进行判断,否则询问下一个问题。
1 | ((atom? (car l)) (lat? (cdr l))) |
第三个问题
询问 else 是否为 \(T\),由于 else 总是为 \(T\),因此返回 #f 的值。
1 | (else #f) |
The First Commandment (prelimilary)
当对一个原子列表 lat 进行递归调用时,询问两个问题 (null? lat) 和 else。