用pi-sum运算数字却报错stringp错误

Operate numbers with pi-sum but report wrong stringp error

我学习了下面的代码模式,它抽象了和

#+BEGIN_SRC scheme :results value
(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))
(define (pi-sum a b)
  (sum (lambda (x) (/ 1.0 (* x (+ x 2))))
       a
       (lambda (x) (+ x 4))
       b))
(pi-sum 1 11)
#+END_SRC

#+RESULTS:
: 0.372005772005772

使用 elisp

#+begin_src emacs-lisp :session sicp :lexical t
(defun sum(term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

(defun pi-sum(a b)
  (sum (lambda (x) (/ 1.0 (* x (+ x 2))))
       a
       (lambda (x) (+ x 4))
       b))
#+end_src

#+RESULTS:
: pi-sum

在传入参数之前似乎效果很好

ELISP> (pi-sum 1 11)
*** Eval error ***  Wrong type argument: stringp, 1

不知道 (pi-sum a b) 中的参数在哪里被指定为字符串?

您的代码正在调用 term 函数,其记录如下:

(term PROGRAM)

Start a terminal-emulator in a new buffer. The buffer is in Term mode; see ‘term-mode’ for the commands to use in that buffer.

如果设置debug-on-error:

,您可以看到错误的详细信息
(setq debug-on-error t)
(pi-sum 1 11)

你会得到这样的回溯:

Debugger entered--Lisp error: (wrong-type-argument stringp 1)
  make-process(:name "terminal" :buffer #<buffer *terminal*> :command ("/bin/sh" "-c" "stty -nl echo rows 25 columns 81 sane 2>/dev/null;if [  = .. ]; then shift; fi; exec \"$@\"" ".." 1))
  apply(make-process (:name "terminal" :buffer #<buffer *terminal*> :command ("/bin/sh" "-c" "stty -nl echo rows 25 columns 81 sane 2>/dev/null;if [  = .. ]; then shift; fi; exec \"$@\"" ".." 1)))
  start-process("terminal" #<buffer *terminal*> "/bin/sh" "-c" "stty -nl echo rows 25 columns 81 sane 2>/dev/null;if [  = .. ]; then shift; fi; exec \"$@\"" ".." 1)
  apply(start-process "terminal" #<buffer *terminal*> "/bin/sh" "-c" "stty -nl echo rows 25 columns 81 sane 2>/dev/null;if [  = .. ]; then shift; fi; exec \"$@\"" ".." 1 nil)
  term-exec-1("terminal" #<buffer *terminal*> 1 nil)
  term-exec(#<buffer *terminal*> "terminal" 1 nil nil)
  make-term("terminal" 1)
  term(1)
  (+ (term a) (sum term (next a) next b))
  (if (> a b) 0 (+ (term a) (sum term (next a) next b)))
  sum((lambda (x) (/ 1.0 (* x (+ x 2)))) 1 (lambda (x) (+ x 4)) 11)
  pi-sum(1 11)

您需要更改 sum 函数以使用 funcall 调用您传递给它的 termnext 函数:

(defun sum(term a next b)
  (if (> a b)
      0
      (+ (funcall term a)
         (sum term (funcall next a) next b))))

根据 sum 的修订定义,调用 pi-sum 给出了预期的答案:

(pi-sum 1 11)
0.372005772005772