开发者

OCaml: Declaring a function before defining it

开发者 https://www.devze.com 2023-04-10 08:26 出处:网络
Is there a way to declare a function before defining it in OCaml?I\'m using an OCaml interpreter. I have two functions:

Is there a way to declare a function before defining it in OCaml? I'm using an OCaml interpreter.

I have two functions:

let myFunctionA = 
(* some stuff here..... *) myFunctionB (*some stuff *)

let myFunctionB = 
(* some stuff here .... *) myFunctionA (* some stuff *)

This doesn't work though, since myFunctionA can't call myFunctionB before it's made.

I've done a few google searches but can't seem to find anyt开发者_开发百科hing. How can I accomplish this?


What you want is to make these two functions mutually recursive. Instead of using "let ... let ...", you have to use "let rec ... and ..." as follows:

let rec myFunctionA = 
(* some stuff here..... *) myFunctionB (*some stuff *)

and myFunctionB = 
(* some stuff here .... *) myFunctionA (* some stuff *)


Actually "let rec .." has a very serious limitation: it only works within a single module. This forces the programmer to write big modules where it is not desired .. a problem which does not occur in lowly C!

There are several workarounds, all unsatisfactory. The first is to make a variable of the function type and initially store a function raising an exception in it, then later store the desired value.

The second is to use class types and classes (and one indirection). If you have a lot of mutually recursive functions this is the best way (because you only need to pass a single object to each of them).

The easiest and most ugly is to pass the functions to each other as arguments, a solution which rapidly gets out of control. In a module following all the definitions you can simplify the calling code by introducing a set of "let rec" wrappers. Unfortunately, this does not help defining the functions, and it is common that most of the calls will occur in such definitions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号