首页 > 解决方案 > `fixed-point` 中的内部 `try` 交互

问题描述

我正在阅读fix-pointSICP:

#+begin_src emacs-lisp :session sicp :lexical t
(defvar tolerance 0.00001)
(defun fixed-point(f first-guess)
  (defun close-enoughp(v1 v2) 
    (< (abs (- v1 v2)) tolerance))
  (defun try(guess) ;;
    (let ((next (funcall f guess)))
      (if (close-enoughp guess next)
          next
          (try next))))
  (try first-guess))
(fixed-point #'cos 1.0)
#+end_src

#+RESULTS:
: 0.7390822985224024

从上面的案例中,我了解到,一个本质while是抽象概念“尝试”

#+begin_src ipython :session sicp :results output pySrc/sicp_fixedpoint2.py
import math

def fixed_point(f, guess):
    while True:
        nex = f(guess)
        if abs(guess-nex) < 0.0001:
            return nex
        else:
            guess = nex #local assignment is nature of lambda
print(fixed_point(math.cos, 1))
#+end_src

#+RESULTS:
: 0.7390547907469174

所以我可以用有效的函数抽象思维在 python 中编写迭代。

反思时try,不仅仅是“尝试是迭代中的一段时间”,它教会了我什么?

它可以在没有的情况下重新构建try,但return fixed_point(f, nex)直接返回。

#+begin_src ipython :session sicp :results output :tangle pySrc/sicp_fixedpoint.py
import math
tolerance = 0.00001

def fixed_point(f, guess):
    def good_enoughp(a, b):
        return abs(a-b) < tolerance

    nex = f(guess)
    if good_enoughp(guess, nex):
        return nex
    else:
        return fixed_point(f, nex)    

print(fixed_point(math.cos, 1))
#+end_src

#+RESULTS:
: 0.7390822985224024

那么为什么try在这里介绍SICP,我猜效率可能不是作者的主要考虑因素。

用 elisp 测试

#+begin_src emacs-lisp :session sicp :lexical t
(defvar tolerance 0.00001)
(defun fixed-point(f guess)
  (defun close-enoughp(v1 v2) ;
    (< (abs (- v1 v2)) tolerance))

  (let ((next (funcall f guess)))
    (if (close-enoughp guess next)
        next
      (fixed-point f next)))
  )
;;(trace-function #'fixed-point)
(fixed-point #'cos 1.0)
#+end_src

#+RESULTS:
: 0.7390822985224024

它按预期工作。

似乎 returnfixed-point f next比带有 try 的内部迭代更干净一些。

SICP在这里的考虑是什么,打算教什么?

标签: python-3.xschemeelispsicpfixed-point-iteration

解决方案


恰恰相反:它更清洁、更高效,try因为它不需要重新定义good-enough-p.

(另外,你不应该在 Python 中使用递归)。


的版本try优于调用顶部函数的版本fixed-point,因为fixed-point包含函数good-enough-p和的内部定义try。一个头脑简单的编译器会编译它,以便在每次调用时它实际上在每次调用时一次又一次地重新定义这些定义。try没有这样的担忧,因为它已经在已经定义fixed-point的内部环境中good-enough-p,因此try可以运行。

(更正/澄清:上面将您的代码视为Scheme,使用 internal defines 而不是带有defuns 的 Common Lisp,毕竟 SICP 是 Scheme。在 Common Lisp / ELisp 中甚至没有问题 -在每次调用封闭函数时,将始终执行internal defuns,只是一遍又一遍地(重新)在顶层定义相同的函数。)

顺便说一句,我喜欢你的 Python 循环翻译,它对 Scheme 的尾递归循环的逐字翻译,一对一。

鉴于您问题中的第一个尾递归方案代码,您的while翻译正是方案编译器应该做的事情。两者完全相同,下至“可怕while True ...的逃脱”,就我个人而言,我非常喜欢它的直接性和清晰性。意思是,我不需要跟踪哪个值被分配给哪个变量以及最终返回哪个变量——相反,一个值只是返回,就像它在 Scheme 中一样。


推荐阅读