Search code examples
schemelispsicp

SICP Exercise 1.11


I can't get the results of the execution.

I think it's repeated indefinitely.

I made a structure by adding 1 to the count and repeating it.

What did I do wrong?

   #lang sicp
   (define (fi n)
    (f-iter 0 3 n))
 
  (define (f-iter sum count n)
    (cond ((= count (+ n 1)) sum)
          ((< count 3) count)
          (+ (f-iter sum (- count 1) n)
             (* 2 (f-iter sum (- count 2) n))
             (* 3 (f-iter sum (- count 3) n))
             sum))
          (+ count 1)
          (f-iter sum count n))

Solution

  • The first thing you need to do is to indent your code correctly:

    (define (f-iter sum count n)
      (cond ((= count (+ n 1)) sum)
            ((< count 3) count)
            (+ (f-iter sum (- count 1) n)
               (* 2 (f-iter sum (- count 2) n))
               (* 3 (f-iter sum (- count 3) n))
               sum))
      (+ count 1)
      (f-iter sum count n))
    

    Let's annotate the code with comments:

    (define (f-iter sum count n)
      (cond ((= count (+ n 1)) sum)
            ((< count 3) count)
            (+ (f-iter sum (- count 1) n)       ; the syntax of COND expects
                                                ; a list with a condition as
                                                ; the first element.
                                                ; here the first element is the
                                                ; function +, which is always true.
                                                ; as such it makes no sense.
    
               (* 2 (f-iter sum (- count 2) n))
               (* 3 (f-iter sum (- count 3) n))
               sum))                            ; here the result of COND is not
                                                ; used anymore. It is not returned from
                                                ; f-iter.
    
      (+ count 1)                               ; this result is never used.
    
      (f-iter sum count n))                     ; this calls the same function with the
                                                ; same arguments. Thus
                                                ; f-iter calls itself
                                                ; indefinitely at this point.