-1

I'm new to OCaml. I have a little exercise for training to get familiar with the notion of mutual recursion in OCaml. The idea of the function I need to write is to be able to count the steps of the function Basically : there's a warehouse with 2 employees who need to get those boxes out. Employee A can take out one box at a time, Employee B can take out 2 boxes at a time if the number of remaining boxes is even. Taking out one box (or two) is one step.

I've tried to use a variable that I try to increment each time one of the function is called.

Here's the code I have so far.

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

So far it kept returning 0 or 1 for employeeA function or 0 or 2 for employeeB function. Although the expected result would be that for 11 boxes for example, if EmployeeA starts, it should return 10 steps, and if EmployeeB starts, 11 steps.

Thanks.

TierTwo
  • 123
  • 2
  • 11

1 Answers1

1

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)
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • Thanks it helped me progress in my answer! However, I think I have a logic problem because I'm running, and the values I have aren't the ones I should. The code I now have is this one : ```let rec employeeA n = if n > 0 && n mod 2 != 0 then 1 + employeeA(n-1) else if n > 0 && n mod 2 = 0 then 1 + employeeB(n-2) else 0 and employeeB n = if n > 0 && n mod 2 = 0 then 1 + employeeB(n-2) else if n > 0 && n mod 2 != 0 then 1 + employeeA(n-1) else 0;; ``` – TierTwo Sep 20 '19 at 22:48