I'm following the Real World OCaml book to learn OCaml and many of the programs require using the Jane Street Core library. When I use functions from this core library in the toplevel, it works great. There, I just use the following commands to open the Core library.
$ #use "topfind";;
#thread;;
#camlp4o;;
#require "core.top";;
#require "core.syntax";;
open Core.Std;;
Then I can run this program line by line in the toplevel and functions like String.split work fine.
# let languages = "OCaml,Perl,C++,C";;
val languages : string = "OCaml,Perl,C++,C"
# let dashed_languages =
let language_list = String.split languages ~on:',' in
String.concat ~sep:"-" language_list
;;
val dashed_languages : string = "OCaml-Perl-C++-C"
But if I put it all in a script, how do I make the compiler recognize the core libraries? So if I'm running the same program in a script:
open Core.Std;;
open Str;;
let languages = "OCaml,Perl,C++,C";;
let dashed_languages =
let language_list = String.split languages ~on:',' in
String.concat ~sep:"-" language_list
;;
Then I compile it:
ocamlopt -o test test.ml
I get an error:
Error: Unbound module Core
So clearly Core is not being recognized. I can't put the #use and #require commands in my script because OCaml doesn't recognize those. So how can I use Core?
Since you're following Real World OCaml, you may want to use corebuild
to compile executables since this is what the book recommends. In this case the command corebuild test.native
should correctly compile your script. If you use libraries other than Core, you'll need to specify them with the -pkg
option.
Also, note you can omit the double semicolons within a .ml
file.
Make sure you have ocamlfind. Also, make sure you have the right environment for it to find packages. If you installed with opam, run "eval opam config env
". Then:
ocamlfind ocamlopt -linkpkg -thread -package core test.ml -o test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With