首页 > 解决方案 > 如何在我的相互递归程序中完成步骤数?

问题描述

我是 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 个步骤。

谢谢。

标签: recursionocamlmutual-recursion

解决方案


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)

推荐阅读