Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml: Declaring a function before defining it

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 anything. How can I accomplish this?

like image 814
Casey Patton Avatar asked Sep 30 '11 16:09

Casey Patton


People also ask

Can I call a function before I define it?

It is not possible. Python does not allow calling of a function before declaring it like C.

What is an anonymous function in OCaml?

Anonymous Functions An anonymous function is a function that is declared without being named. These can be declared using the fun keyword, as shown here. (fun x -> x + 1);; - : int -> int = <fun> OCaml.

What does -> mean in OCaml?

The way -> is defined, a function always takes one argument and returns only one element. A function with multiple parameters can be translated into a sequence of unary functions.


1 Answers

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 *)
like image 133
Martin Jambon Avatar answered Sep 21 '22 05:09

Martin Jambon