什么情况需要用let代替let*?

What situations require let instead of let*?

我正在阅读 "Common Lisp: A Gentle Introduction to Symbolic Computation"。

第 5 章介绍了 letlet* 并讨论了它们之间的区别,并特别指出您可能会误以为总是使用 let* 而不是 let,但您不应该这样做,原因有二:

  1. let 更容易理解,因为它暗示没有依赖关系。
  2. 5.6节说了存在let是唯一正确选择的情况,但是没有细说

实际上,它说:

There are some situations where LET is the only correct choice, but we won't go into the details here. Stylistically, it is better to use LET than LET* where possible, because this indicates to anyone reading the program that there are no dependencies among the local variables that are being created. Programs with few dependencies are easier to understand.

那么,现在我的问题是:在哪些情况下 let 是唯一正确的选择?

主要是你想引用哪个变量。

(let ((p 'foo))
   (let or let*    ; use of those
       ((p 'bar)
        (q p))     ; which p do you want? The first or the second?
     (list p q)))

试一试:

CL-USER 60 > (let ((p 'foo))
               (let ((p 'bar)
                     (q p))
                 (list p q)))
(BAR FOO)

CL-USER 61 > (let ((p 'foo))
               (let* ((p 'bar)
                      (q p))
                 (list p q)))
(BAR BAR)

另请注意 LET 中存在间接依赖关系:绑定的值从左到右求值:

(let ((list '(1 2)))
  (let ((a (pop list))
        (b (pop list)))
   (list a b)))

以上表格的结果总是(1 2)