[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Running OCaml scripts from the command line



On Tue, Feb 21, 2012 at 5:56 PM, Sebastian Probst Eide
<sebastian.probst.eide@xxxxxxxxx> wrote:
> Dear OCamlers.
> I am doing some quick and dirty OCamling, and while coding would like to
> execute my code in the toplevel, rather than first compiling it and then
> running my compiled binary.
>
> if I have a file called test1.ml, for which the following works fine:
>
> ocaml test1.ml

On my machine this does not execute in the top level. That merely runs the code
in the file(1) and exits.

Consider the sh session:
raphael ~ $ cat toto.ml
print_endline "blah"
raphael ~ $ ocaml toto.ml
blah
raphael ~ $ ocaml
        Objective Caml version 3.12.0

# #use "toto.ml" ;;
blah
- : unit = ()
#


Running "in the top level" is achieved by the #use primitive. (Also, toplevel
has two meaning in OCaml: a toplevel definition is a definition not nested under
any scope and *the* toplevel is the interactive read-compile-execute-print
loop.)

>
> But, now, if test1.ml uses the Test2 module (in test2.ml), I get a module
> missing exception. I get around this with:
>
> ocaml test2.ml test1.ml
>
> but when supplying both test2 and test1 to the ocaml toplevel, absolutely no
> code is executed at all.

That is not true. The code in test2.ml is executed (or at least it is on my
machine):

raphael ~ $ cat tata.ml
print_endline "fooooooooooo"
raphael ~ $ ocaml toto.ml tata.ml
blah

And also consider:

raphael ~ $ ocaml
        Objective Caml version 3.12.0

# #use "toto.ml" ;;
blah
- : unit = ()
# #use "tata.ml" ;;
fooooooooooo
- : unit = ()
#


> I have tried to use the -I flag to add the current directory to the search
> path (which it should be by default?), but without any luck.
>
> I haven't had any luck with ocamlfind either, and ocamlfind seems to be for
> finding third party libraries, rather than other modules within the same
> project?

You can try ocamlbuild. If your project is simple enough it will make a binary
out of anything.

To build a native executable out of the test1.ml, just type:

$ ocamlbuild test1.native

(replace by test1.byte for the slower but more portable bytecode version.)

It should figure out the dependencies if they are in the same directory and give
you a nice executable.

>
> I hope I am missing something trivial here.
>

$ echo "Module Test2 = struct" > one_file.ml
$ cat test2.ml >>one_file.ml
$ echo "end" >>one_file.ml
$ cat test1.ml >>one_file.ml
$ ocaml one_file.ml

This is quick and dirty. Don't use it.



(1) what it really does is compile the content to byte-code and runs it in the
ocaml VM. Code is not interpreted.

> Thank you, and have a great afternoon!
>
> All the best,
> Sebastian
>
>



-- 
_______
Raphael



 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.