我了解了以下抽象和的代码模式
#+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模式;有关在该缓冲区中使用的命令,请参见“ term-mode”。
如果设置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 [ $1 = .. ]; 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 [ $1 = .. ]; 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 [ $1 = .. ]; 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 [ $1 = .. ]; 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
调用要传递给它的term
和next
函数:
(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