No idea how to solve SICP exercise 1.11

后端 未结 6 1633
感动是毒
感动是毒 2021-02-01 03:59

Exercise 1.11:

A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n - 1) + 2f(n - 2)

6条回答
  •  时光说笑
    2021-02-01 04:39

    I'm going to come at this in a slightly different approach to the other answers here, focused on how coding style can make the thought process behind an algorithm like this easier to comprehend.

    The trouble with Bill's approach, quoted in your question, is that it's not immediately clear what meaning is conveyed by the state variables, a, b, and c. Their names convey no information, and Bill's post does not describe any invariant or other rule that they obey. I find it easier both to formulate and to understand iterative algorithms if the state variables obey some documented rules describing their relationships to each other.

    With this in mind, consider this alternative formulation of the exact same algorithm, which differs from Bill's only in having more meaningful variable names for a, b and c and an incrementing counter variable instead of a decrementing one:

    (define (f n)
        (if (< n 3)
            n
            (f-iter n 2 0 1 2)))
    
    (define (f-iter n 
                    i 
                    f-of-i-minus-2
                    f-of-i-minus-1
                    f-of-i)
        (if (= i n)
            f-of-i
            (f-iter n
                    (+ i 1)
                    f-of-i-minus-1
                    f-of-i
                    (+ f-of-i
                       (* 2 f-of-i-minus-1)
                       (* 3 f-of-i-minus-2)))))
    

    Suddenly the correctness of the algorithm - and the thought process behind its creation - is simple to see and describe. To calculate f(n):

    • We have a counter variable i that starts at 2 and climbs to n, incrementing by 1 on each call to f-iter.
    • At each step along the way, we keep track of f(i), f(i-1) and f(i-2), which is sufficient to allow us to calculate f(i+1).
    • Once i=n, we are done.

提交回复
热议问题