recursion - 如何在我的相互递归程序中完成步骤数?
问题描述
我是 OCaml 的新手。我有一些训练练习来熟悉 OCaml 中相互递归的概念。我需要编写的函数的想法是能够计算函数的步骤基本上:有一个仓库有 2 名员工需要把这些盒子拿出来。员工 A 一次可以取出一箱,如果剩余箱子数为偶数,员工 B 一次可以取出 2 箱。取出一盒(或两盒)是一步。
我尝试使用一个变量,每次调用其中一个函数时我都会尝试递增该变量。
这是我到目前为止的代码。
let rec employeeA n =
let x = 0 in
if n > 0 && n mod 2 = 0 then
x + 1 + employeeB(n-2)
else
0
and employeeB n =
let x = 0 in
if n > 0 && n mod 2 != 0 then
x + 1 + employeeA(n-1)
else
0;;
到目前为止,它一直为 employeeA 函数返回 0 或 1,或者为 employeeB 函数返回 0 或 2。尽管预期的结果是,例如,对于 11 个框,如果 EmployeeA 启动,它应该返回 10 个步骤,如果 EmployeeB 启动,它应该返回 11 个步骤。
谢谢。
解决方案
If you look at this part of the code:
if n > 0 && n mod 2 = 0 then
x + 1 + employeeB(n-2)
else
0
You're saying that if the number of boxes isn't even, it takes 0 steps to handle them. This can't be right. I'd say you need to call employeeB
if n > 0 and is not even.
Generally speaking you need to keep in mind that variables in OCaml are immutable. You don't really need to say:
let x = 0 in
... x + 1 + employeeB (n - 2)
Since x
is immutable, it will always be 0. So this is the same as just saying:
1 + employeeB (n - 2)
推荐阅读
- linux - 自动删除目录中的文件夹删除错误的文件夹
- html - 自动化响应图像
- react-native - react-navigation 访问 cardStyleInterpolator 中的导航状态
- firebase - Cloud Functions 中的 Firestore - 通过错误消息创建缺少的索引
- vbscript - 为什么当我使用 webbrowser.visible = true 时我的机器人不可见
- mediawiki - 本地域上的 LDAP 与 Debian 10 上的 Mediawiki
- sql - 如何在 SQL 中进行子查询
- python - 使用 FPDF 生成发票
- react-native-flexbox - 使用 React Native 覆盖样式表中的单个样式道具
- html - 如何在 div 中的图标下方获取我的文本