gpt4 book ai didi

lisp - 用于动态范围?

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

我一直在尝试使用 emacs lisp,有时让我感到困惑的一件事是动态范围。它有很大的 future 吗?我知道的大多数语言都使用静态作用域(或者已经转向静态作用域,比如 Python),可能是因为我更了解它,所以我更喜欢它。是否存在动态范围更有用的特定应用程序/实例或示例?

最佳答案

这个问题有很好的讨论here .与您的问题相关的最有用的部分是:

Dynamic bindings are great for modifying the behaviour of subsystems. Suppose you are using a function ‘foo’ that generates output using ‘print’. But sometimes you would like to capture the output in a buffer of your choosing. With dynamic binding, it’s easy:

(let ((b (generate-new-buffer-name " *string-output*"))))
(let ((standard-output b))
(foo))
(set-buffer b)
;; do stuff with the output of foo
(kill-buffer b))

(And if you used this kind of thing a lot, you’d encapsulate it in a macro – but luckily it’s already been done as ‘with-output-to-temp-buffer’.)

This works because ‘foo’ uses the dynamic binding of the name ‘standard-output’, so you can substitute your own binding for that name to modify the behaviour of ‘foo’ – and of all the functions that ‘foo’ calls.

In a language without dynamic binding, you’d probably add an optional argument to ‘foo’ to specify a buffer and then ‘foo’ would pass that to any calls to ‘print’. But if ‘foo’ calls other functions which themselves call ‘print’ you’ll have to alter those functions as well. And if ‘print’ had another option, say ‘print-level’, you’d have to add that as an optional argument as well… Alternatively, you could remember the old value of ‘standard-output’, substitute your new value, call ‘foo’ and then restore the old value. And remember to handle non-local exits using ‘throw’. When you’re through with this, you’ll see that you’ve implemented dynamic binding!

也就是说,对于 99% 的情况,词法绑定(bind)是恕我直言要好得多。请注意,现代 Lisp 不像 Emacs lisp 那样仅支持动态绑定(bind)。

  • Common Lisp 支持两种形式的绑定(bind),尽管词法绑定(bind)使用得更多
  • Scheme 规范甚至没有指定动态绑定(bind)(只有词法绑定(bind)),尽管许多实现都支持这两种绑定(bind)。

此外,受 Lisp 启发的现代语言(如 Python 和 Ruby)通常以直接的方式支持词法绑定(bind),动态绑定(bind)也可用,但不太直接。

关于lisp - 用于动态范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2979428/

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