我试图弄清楚如何将3个变量合并到球拍的尾部递归代码中 [英] I'm trying to figure out how to incorporate 3 variables into my tail recursion code for racket

查看:81
本文介绍了我试图弄清楚如何将3个变量合并到球拍的尾部递归代码中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个称为popadd的尾递归函数,该函数在时间t = 0时以P个人口为模型,每年增加d个人口.

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)) 
)

但是,当然,我得到尚未定义d的错误,这是正确的.我尝试将其添加为输入,但作为返回,我得到了为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.

推荐答案

您可以简单地将另一个参数传递给递归:

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))))

请注意,如果可以,您可以对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.

这篇关于我试图弄清楚如何将3个变量合并到球拍的尾部递归代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆