首页 > 解决方案 > 方案 if 表达式返回 '#' 如果正文包含表达式

问题描述

所以我目前正在阅读 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)

问题是当我运行这个程序时它工作正常,直到它找到一个素数。我使用的解释器是球拍,程序以:

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: #<void>
  arguments...:
   3
1019 *** 0

如果我正确理解解释器,它应该根据应用顺序评估原则评估这个表达式,对吗?那么为什么将if表达式作为过程传递给我的search-for-primes过程呢?我在这里想念什么?

标签: schemesicp

解决方案


问题在于search-for-primes,如果您在 an 的一条腿中有多个表达式if,那么您需要将它们放在一个begin块内 - 用它包围它是()行不通的。这应该可以解决问题:

(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))))))

推荐阅读