Newbie question: Core and Base

I’ve started to read Real World Ocaml. I installed opam, ocaml 5.2, core, and utop. When I start utop and “open Base” it works. When I start ocaml and “open Base”, it says “Unbound module Base”. I sure didn’t expect to see a difference there. I fear that if ocaml can’t ‘open Base’, ocamlc won’t be able to either, and nothing will compile.

There must be a simple answer. Please tell me what it is.

1 Like

To make the compiler see the dependency you need to declare that you depend on the findlib package base (this goes for all third-party packages, not just base).

How to do that depends on the way you build your project.

1 Like

That tells me how to make ocamlc ‘open Base’, I suppose, once I find out how to do dune. But what about opening Base in ocaml interactively? Or should I just not do that, and use utop instead?

1 Like

If you use dune utop it will launch utop with the packages that you depend in your project, otherwise you can also call

#require "base";;

in the Toplevel (or UTop) to load the dependency by hand. utop also has a require flag that does this automatically.

1 Like

Note: #require is not a normal directive for ocaml. It is only made available if you use some scripts provided by the findlib library which is part of ocamlfind.
So from a vanilla ocaml prompt, assuming that you have installed the opam package ocamlfind, you can do #use "topfind";; then #require "base";; and after that you can use Base as you wish, for instance through open Base;;.

For ocamlc, the issue will come up again; the solution is a bit different. You can use ocamlfind as your driver for the compilers: ocamlfind ocamlc -package base -c my_file.ml for compile-only commands, ocamlfind ocamlc -package base -linkpkg -o my_exe my_file.cmo to produce an executable (if you replace my_file.cmo with my_file.ml in the last command you can compile and link at the same time).

2 Likes

Ah, thank you very much. I understand what to do, I think.

1 Like

Should we add instructions how to use vanilla toplevel to Installing OCaml · OCaml Documentation ?

1 Like

As a beginner, there’s no reason for you to be using vanilla ocaml as your REPL. Just use utop. It’s the documented and recommended path.

As for compiling with Core and Base in projects, same story. Follow the documentation and use dune, which will take care of these details for you.

Don’t borrow trouble you don’t need :wink:

1 Like

If I were OP, I’d take this advice to its full extent and follow the Learn OCaml docs in that they correctly label RWO as an intermediate book, not for beginners :grin:

1 Like