简体   繁体   中英

Why does this result in an infinite loop [SICP]?

I am working on a problem from SICP. I am not sure why this function results in an infinite while loop. Can someone please shed some light on this? I am sure there might be better ways to write this loop, but I am new to functional programming and still trying to wrap my head around writing loops like this.

(define (search-for-primes a b)
        (if (> a b) (display " Done"))
        ((timed-prime-test a) (search-for-primes (+ a 1) b)))

The program keeps printing "Done" for this input: (search-for-primes 2 10), which makes no sense. 'timed-prime-test' is a function which checks whether an input is a prime no. or not. Here's what I thinking: the program keeps calling itself until a = 11, at which point it would quit. However, even for the first 9 iterations (a=2 to a=10), I see no output from 'timed-prime-test' function and this indicates to me that the control is not even reaching the 2nd line, but then how is the function call happening infinite times?

Edit: I was looking at the syntax of 'if' in the book again and I noticed two things: a) 'alternative' is my code is outside the if block which is wrong. I fixed this but the program output for a = 10. b) A footnote says that it should only have single expressions. Does this behavior of my program has to do with b)? If yes, how does the program execution happen in this case?

If you format your code properly the answer will be immediately clear. This is why formatting your code properly is important . Here's your definition with better formatting:

(define (search-for-primes a b)
  (if (> a b)
      (display " Done"))
  ((timed-prime-test a) (search-for-primes (+ a 1) b)))

So, (search-for-primes 1 1) :

  • tests if 1 is more than 1... it's not;
  • and then starts to evaluate ((timed-prime-test a) (search-for-primes (+ a 1) b)) , to do which:
    • evaluates (timed-prime-test 1) and (search-for-primes 2 1) in some order, which at least means evaluating (search-for-primes 1 1) , which:
      • tests if 2 is more than 1... it is
        • so it prints "Done";
      • and then starts to evaluate... oops.

Now it should be obvious what the problem is here.

((timed-prime-test a) (search-for-primes (+ a 1) b))

The current continuation of the recursive call of (search-for-primes (+ a 1) b) is ((timed-prime-test a) _) but it never reaches the _ because you never fill its value, ie the value of _ is a bottom type . So also the value of ((timed-prime-test a) _) is a bottom.

But the value of search-for-primes is the value of ((timed-prime-test a) _) . So it has no value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM