No idea how to solve SICP exercise 1.11

后端 未结 6 1616
感动是毒
感动是毒 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:33

    Since the post you linked to describes a lot about the solution, I'll try to only give complementary information.

    You're trying to define a tail-recursive function in Scheme here, given a (non-tail) recursive definition.

    The base case of the recursion (f(n) = n if n < 3) is handled by both functions. I'm not really sure why the author does this; the first function could simply be:

    (define (f n)
       (f-iter 2 1 0 n))
    

    The general form would be:

    (define (f-iter ... n)
       (if (base-case? n)
           base-result
           (f-iter ...)))
    

    Note I didn't fill in parameters for f-iter yet, because you first need to understand what state needs to be passed from one iteration to another.

    Now, let's look at the dependencies of the recursive form of f(n). It references f(n - 1), f(n - 2), and f(n - 3), so we need to keep around these values. And of course we need the value of n itself, so we can stop iterating over it.

    So that's how you come up with the tail-recursive call: we compute f(n) to use as f(n - 1), rotate f(n - 1) to f(n - 2) and f(n - 2) to f(n - 3), and decrement count.

    If this still doesn't help, please try to ask a more specific question — it's really hard to answer when you write "I don't understand" given a relatively thorough explanation already.

提交回复
热议问题