Here is a simple example of how a main method can be implemented to run when using ocamlc and ocamlrun, but not when using the interactive interpreter (ocaml). The factorial example is used here again with the main method modifications.
Factorial(w/ main) Source (download):
(* Factorial Program w/ main *) (* Define the factorial function *) let rec fact(n) = if(n=0) then 1 else n * fact(n-1);; (* main function checks for correct arguments and attempts to find the factorial of the supplied argument. The try...with statement catches the int_of_string exception if the argument is not numeric. *) let main () =
if Array.length Sys.argv <> 2 then begin
print_string "Usage: factmain <number>";
print_newline ()
end else begin
try
print_string("Factorial of ");
print_int(int_of_string Sys.argv.(1));
print_string(" is ");
print_int(fact (int_of_string Sys.argv.(1)));
print_newline ()
with Failure "int_of_string" ->
print_string "Bad integer constant";
print_newline ()
end
;; (* If using ocamlc and ocamlrun call main, otherwise do nothing if in ocaml interpreter. If in interpreter, user can call fact function manually *) if !Sys.interactive then () else main ();;
Factorial (w/ main) Output:
canopus:~/ta/505/examples/fact> ocamlc -g -o factmain factmain.ml
canopus:~/ta/505/examples/fact> ./factmain
Usage: factmain <number>
canopus:~/ta/505/examples/fact> ./factmain 4
Factorial of 4 is 24
canopus:~/ta/505/examples/fact> ./factmain a
Factorial of Bad integer constant