Search code examples
ocaml

Why does my recursion never terminate in OCaml?


let qrec=Queue.create ()

let rec queueaddrec1 n=
 if n==1 then
  Queue.add 1 qrec
 else
  Queue.add n qrec;
  queueaddrec1 (n-1)

let ()=
 queueaddrec1 5;
 Queue.iter print_int qrec;

VScode told me the following line will never return. I don't why. When I ran it I got a endless loop.

queueaddrec1 5

If I write this:

let rec queueaddrec2 n=
 if n>1 then
  Queue.add n qrec;
  queueaddrec (n-1)
 else
  Queue.add 1 qrec

I get another error:

This expression has type 'a but an expression was expected of type 
('b->'b Queue.t->unit)->int->int Queue.t->'a
The type variable 'a occurs inside
('a->'a Queue.t->unit)->int->int Queue.t->'b

Solution

  • You should use a code formatting tool: your indentation is lying to you. Correctly indented and removing the use of == (which is not the equality that you want), the first version of your function reads:

    let rec queueaddrec1 n=
     if n=1 then
      Queue.add 1 qrec
     else
      Queue.add n qrec;
     queueaddrec1 (n-1)
    

    You need parentheses to make the whole sequence

    Queue.add n qrec; queueaddrec1 (n-1)
    

    part of the else branch.

    Your second version is not syntactically valid, correctly indented and without superfluous spaces it reads as

    let rec queueaddrec2 n=
     if n>1 then
      Queue.add n qrec;
     queueaddrec (n-1) else Queue.add 1 qrec
    

    with a keyword else appearing outside of any if ... then ... .