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

前端 未结 2 1221
囚心锁ツ
囚心锁ツ 2021-01-23 19:37

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         


        
2条回答
  •  -上瘾入骨i
    2021-01-23 20:32

    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.

提交回复
热议问题