How to use OCaml as a script language?

How to use OCaml as a script language like bash and python? It will be good that I can write a script in OCaml and directly invoke it.

For example, I write a script named "script.ml" and then I can invoke it directly by

 $ ./script.ml

Thanks!

asked May 2, 2013 by Adam (1,780 points)

1 Answer

 
Best answer

Three helloworld scripts:

script3.ml

#! /usr/bin/env ocaml

print_string "Hello world!\n";;

script1.ml:

#! /bin/ocaml

print_string "Hello world!\n";;

script2.ml

#! /bin/sh
# (*
exec ocaml "$0" "$@"
*) use "topfind";;

print_string "Hello world!\n";;

Idea from findlib quickstart.

Remember to make the executable by

chmod 755 script.ml

I prefer script3.ml. The script1.ml is straightforward, but it is bounded to /bin/ocaml for the ocaml command. The script2.ml is more complex, but use your environmental configuration for the location of the ocaml command.

Also be aware that the overall source code is compiled in total first and then is executed. Hence, no execution happens if there is some error, such as failures to compile the script. This is different from a bash script that will be executed by the interpreter until there is an error happens.

There are other discussions and tools on using OCaml as a scripting language:

OCaml as a scripting language.
ocamlscript: natively-compiled OCaml scripts.

answered May 3, 2013 by anonymous
edited May 26, 2013

Most preferred script:

$ cat script3.ml 
#! /usr/bin/env ocaml

print_string "Hello world!\n";;
commented May 26, 2013 by anonymous

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...