Scheme 如果表达式返回'#&书信电报;无效>';如果主体包含表达式

Scheme 如果表达式返回'#&书信电报;无效>';如果主体包含表达式,scheme,sicp,Scheme,Sicp,因此,我目前正在阅读SICP,我被困在练习1.22中,因为我不明白为什么我的程序不能按我预期的方式工作。这是密码 #lang sicp ; the given function to time the search for a prime (define (timed-prime-test n) (newline) (display n) (start-prime-test n (runtime))) (define (start-prime-test n start-t

因此,我目前正在阅读SICP,我被困在练习1.22中,因为我不明白为什么我的程序不能按我预期的方式工作。这是密码

#lang sicp
; the given function to time the search for a prime
(define (timed-prime-test n)
    (newline)
    (display n)
    (start-prime-test n (runtime)))
(define (start-prime-test n start-time)
    (if (prime? n)
        (report-prime (- (runtime) start-time))))
(define (report-prime elapsed-time)
    (display " *** ")
    (display elapsed-time))

; finds the smallest natural number that can divide n without any remainder
(define (smallest-divisor n)
    (define (square x)
        (* x x))
    (define (divides? a b)
        (= (remainder a b) 0))
    (define (find-divisor n test-divisor)
        (cond ((> (square test-divisor) n) n)
              ((divides? n test-divisor) test-divisor)
              (else (find-divisor n (+ test-divisor 1)))))
    (find-divisor n 2))

; returns true if the given number n is prime
(define (prime? n)
    (= n (smallest-divisor n)))

; start searching at start and found keeps track of the amount of
; primes found, if it equals 3 return found
(define (search-for-primes start found)
    (if (= found 3)
        found   ; after finding 3 primes above start return
        ((timed-prime-test start)    ; if not continue search with start + 1
         (search-for-primes (+ start 1) (if (not (prime? start))
                                            found
                                            (+ found 1))))))

(search-for-primes 1000 0)
问题是,当我运行这个程序时,它工作正常,直到找到一个素数。我使用的解释器是racket,程序以以下方式终止:

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: #<void>
  arguments...:
   3
1019 *** 0
应用:不是程序;
应为可应用于参数的过程
鉴于:#
论据。。。:
3.
1019 *** 0

如果我正确理解了解释器,那么它应该根据应用顺序求值原则来计算这个表达式,对吗?那么为什么它要将
if
表达式作为一个过程传递给我的
搜索素数的过程呢?这里我遗漏了什么?

问题在于
搜索素数
,如果
if
的一个分支中有多个表达式,则需要将它们放在
开始
块中-用
()
包围它将不起作用。这应该可以解决问题:

(define (search-for-primes start found)
  (if (= found 3)
      found
      (begin ; add this!
        (timed-prime-test start)
        (search-for-primes (+ start 1) (if (not (prime? start))
                                           found
                                           (+ found 1))))))

我不确定作者是否打算使用
begin
来解决问题,但除此之外:这解决了我的问题!thanks@emn我认为作者是想让你用不同的时间来测量时间,而不是在函数的中间。您应该在调用点外部测量它,这样您就不需要使用
begin