I'm trying to figure out how to incorporate 3 variables into my tail recursion code for racket

旧巷老猫 提交于 2019-12-04 05:19:39

问题


Write a tail recursive function called popadd that models a population with P people at time t = 0 and adds d people per year.

(define (popadd t  P)
  (if (= t 0)
      P
  (+(popadd( - t 1) P)d)) 
)

but, of course, I get the error that d hasn't been defined yet, which is true. I tried adding it as an input, but as a return I get the number inserted for D.


回答1:


You can simply pass along another parameter to the recursion:

(define (popadd t P d)
  (if (= t 0)
      P
      (+ d (popadd (- t 1) P d))))

Or you can define the value, to avoid passing it around - assuming it doesn't need to change:

(define d 100)

(define (popadd t P)
  (if (= t 0)
      P
      (+ d (popadd (- t 1) P))))

Notice that you could do the same with P, if it's ok. It really depends on what's the expected contract for the procedure.




回答2:


Note that neither your code nor the code in the other answer is tail-recursive: in a recursive call like (+ (f ...)), f is not in tail position. To make the code tail-recursive you need the result of the recursive call be the result of the overall call (so in the above example, + is in tail position). To do this you need an auxiliary function. Here is a way of doing it which relies only on local define:

(define (popadd t P d)
  (define (popadd-loop tau pop)
    (if (zero? tau)
        pop
        (popadd-loop (- tau 1) (+ pop d))))
  (popadd-loop t P)) 

Here is essentially the same thing using named-let, which is nicer:

(define (popadd t P d)
  (let popadd-loop ([tau t] [pop P])
    (if (zero? tau)
        pop
        (popadd-loop (- tau 1) (+ pop d)))))

Finally note that this problem has a closed-form solution:

(define (popadd t P d)
  (+ P (* t d)))

I really wish that people trying to teach programming knew enough maths to not set problems which have trivial closed-form answers, as doing so encourages people to write inefficient (in the complexity-class sense) code. Obviously this is not your fault: it's your teacher's.



来源:https://stackoverflow.com/questions/55643363/im-trying-to-figure-out-how-to-incorporate-3-variables-into-my-tail-recursion-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!