Search code examples
if-statementrecursionocaml

Why does the last "else" not restart the recursion with the new values?


So im learning Ocaml at University and this year the code we create have some special rules : no loops or arrays(i dont know why but she almost seemed angry when a friend of mine used them at the exam so) so we must handle the problems with only recursion and here i must create a code to return all twin prime numbers such as 3,5 5,7 or 11,13 that are between (0,2) and (n,n+2) so i tried to do it this way :

let rec calculpj p q n =
  if q = p + 2 && n > 0 then  
    begin
      if q mod p != 0 && p mod q != 0 then 
        begin 
          print_int(p) ; 
          print_int(q) 
        end
      else 
        calculpj (p + 1) (q + 1) (n - 1) 
    end
  else 
    calculpj (p + 1) (q + 1) (n - 1) ;;
      
calculpj 3 5 3

but for a reason i cant understand why the last "else" dont restart the recursion with the new values since the first "loop" return the value as intented. And if anyone want to know where this exercice come from it is from an exam where the teacher didnt gave us the answers so i dont have anything to correct myself.

I tried a lot of things but since im new to Ocaml i dont know how to find what cause my problem.


Solution

  • You have several cases. One of them is this:

    begin 
    print_int(p) ; 
    print_int(q)
    end
    

    This covers the case where the two mod values aren't 0. Note that this case stops here. There is nothing to do after printing the two ints. This is why your code stops after the first time. The two recursive calls to calculpj are for other cases.

    Other observations:

    The usual not-equal operator in OCaml is <>. You're using one that should be avoided until later in your studies :-)

    You test whether n > 0, which makes sense. But when it's false you're calling calculpj recursively anyway. This suggests that if you fix your first problem you'll have an infinite loop instead.

    It's not clear why you're testing whether q = p + 2. If you supply two values that differ by 2, then your recursive calls will cause them to always differ by 2.