I learned the following code pattern which abstract sum
#+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
With 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
It seem works good until pass in arguments
ELISP> (pi-sum 1 11)
*** Eval error *** Wrong type argument: stringp, 1
Have no ideas where arguments in (pi-sum a b)
are specified as string?
Your code is calling the term
function, which is documented as follows:
(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.
You can see the details of the error if you set debug-on-error:
(setq debug-on-error t)
(pi-sum 1 11)
You'll get a backtrace like this:
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)
You need to change your sum
function to use funcall
to call the term
and next
functions you're passing to it:
(defun sum(term a next b)
(if (> a b)
0
(+ (funcall term a)
(sum term (funcall next a) next b))))
With this revised definition of sum
, calling pi-sum
gives the expected answer:
(pi-sum 1 11)
0.372005772005772