gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:34 25 4
gpt4 key购买 nike

我目前正在阅读“Common Lisp:符号计算的简要介绍”。

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

  1. let 更容易理解,因为它暗示没有依赖关系。
  2. Section 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 中存在间接依赖关系:绑定(bind)的值从左到右求值:

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

以上形式的结果总是(1 2)

关于lisp - 什么情况需要用let代替let*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com