Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The main function in OCaml

Tags:

main

scala

ocaml

From a programmer trained in a C world, this is my main method for OCaml.

let main () = 
    Printf.printf "Hello, world - %d %s\n" (Array.length Sys.argv)  Sys.argv.(0)
    ;;

main ()

However, this code just works fine with ocaml/ocamlc/ocmalopt.

Printf.printf "Hello, world - %d %s\n" (Array.length Sys.argv)  Sys.argv.(0)
;;

What's the logic behind this? Is OCaml something like script language (even though it compiles into binary with ocamlc or ocamlopt) in that it doesn't need main function?

Compared to Scala, we can extend from App in order not to define main method.

object Hello extends App {
    class A

    println(new A() getClass())
    print("Hello, world")
}

Even in this case, we need to have Hello.main(args) when executing it in interpreter mode: i.e., scala hello.scala. OCaml doesn't seem to need any change in ocaml (interpreted), ocamlc and ocamlopt (compiled).

So, do we need main function in OCaml? If so, does OCaml just generates code from the start of the code to the end? If so, how OCaml finds the main code with multiple source code?

like image 663
prosseek Avatar asked Feb 25 '15 05:02

prosseek


2 Answers

OCaml is vaguely like a scripting language in that any top-level expressions are evaluated when you start up the program. It's conventional to have a function named main that invokes the main work of your program. But it's not necessary at all.

Expressions are evaluated in the order that the OCaml files appeared in when they were linked into an executable. Very often this means that the call to main is the last thing that happens when starting the program. Other files often appear before the one containing main, and any top-level code of these files will be executed first.

like image 83
Jeffrey Scofield Avatar answered Sep 27 '22 16:09

Jeffrey Scofield


No, a main function is not needed in OCaml, and it does parse the code from start to end.

When you have multiple files, you would need to compile them in order (or using forward refs)

like image 29
Secret Avatar answered Sep 27 '22 17:09

Secret