Using `ocaml` and `ocamlfind` to run scripts without #-directives

I’d like to use the ocaml binary to run a script using 3rd-party
libraries. I have OCaml 5.3.0. I’d like my script not to contain any
“#”-directives, as these are not recognized by my editor.

In particular, I’d like to load the feather library. This should be accomplished by:

#use "topfind";;
#require "feather";;

and indeed running these commands work as expected in the top-level.

Now is there a way to do:

$ ocaml <OPTIONS?> my_script.ml

such that feather is loaded when my_script.ml? I tried doing

$ ocaml -e '#use "topfind";; #require "feather"' my_script.ml

This produces no output and doesn’t seem to run my_script.ml.
I tried putting the use/require-directives in a separate init file:

$ ocaml -init my_script.init my_script.ml

where my_script.init contains:

#use "topfind";;
#require "feather";;

but I get Unbound module Feather.

I did get it to work by simply concatenating the two files together
and piping it to ocaml:

$ ocaml <(cat bin/rebase_default.init bin/rebase_default.ml)

this works, but it does feel unsatisfactory.

1 Like

Indeed. But I think you have pretty much exhausted the possibilities here. I always feel that ocaml is missing a great opportunity not to be more friendly to writing scripts. But doing so would require quite a bit of good and well coordinated design, not something the eco-system is known for (and backward compatibility problems quickly quick in).

Problems abound,type checkability, mess and no proper strategy around exit codes, and of course the split you mention between compilable sources and non-compilable ones with directives.

Regarding the latter either the compiler could be changed to accept them (which has been suggested a couple of times, can’t find a reference right now) or it could be solved by defining floating attributes for them which the ocaml interpreter would transform into equivalent #require directives (that would still leave the problem of the #! though). I think I initially had that design in b0caml but I eventually came back to directives, not sure exactly why. But perhaps because I wanted to reuse as much as possible the existing directives and that at some point merlin seemingly had no problem with them.

2 Likes