1
votes

So I am currently reading SICP and I am stuck at exercise 1.22, since I do not understand why my program isn't working the way I intend it to work. Here is the Code

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

The problem is that when I run this program it works fine until it finds a prime number. The interpreter that I use is racket and the program terminates with:

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

If I understand the interpreter correctly than it should evaluate this expression according to the applicative-order evaluation principle right? So why is it passing the if expression as a procedure to my search-for-primes procedure? What am I missing here?

1

1 Answers

1
votes

The problem is in search-for-primes, if you have more than one expression in one of the legs of an if, then you need to put them inside a begin block - surrounding it with () won't work. This should fix the problem:

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