Search code examples
recursionocamlmutual-recursion

How to call two functions and use their results as arguments for each other?


I have code:

let join a ~with':b ~by:key = 
  let rec a' = link a ~to':b' ~by:key
      and b' = link b ~to':a' ~by:(Key.opposite key) in
  a'

and compilation result for it is:

Error: This kind of expression is not allowed as right-hand side of `let rec' build complete

I can rewrite it to:

let join a ~with':b ~by:key = 
  let rec a'() = link a ~to':(b'()) ~by:key
      and b'() = link b ~to':(a'()) ~by:(Key.opposite key) in
  a'()

It is compilable variant, but implemented function is infinitely recursive and it is not what I need.

My questions: Why is first implementation invalid? How to call two functions and use their results as arguments for each other?

My compiler version = 4.01.0


Solution

  • The answer to your first question is given in Section 7.3 of the OCaml manual. Here's what it says:

    Informally, the class of accepted definitions consists of those definitions where the defined names occur only inside function bodies or as argument to a data constructor.

    Your names appear as function arguments, which isn't supported.

    I suspect the reason is that you can't assign a semantics otherwise. It seems to me the infinite computation that you see is impossible to avoid in general.