Reputation: 35321
I've wanted to learn OCaml for many years, and I recently decided to finally go for it, but my first real exposure to OCaml has not been auspicious...
I'm using a set of exercises to learn it (an approach that has worked well for me with other languages). Each exercise comes with a test script. The very first test script is this:
(* test.ml *)
open Core.Std
open OUnit2
open Mymod
let ae exp got _test_ctxt = assert_equal ~printer:String.to_string exp got
let tests = ["hello" >:: ae "hello!" (echo "hello!");]
let () =
run_test_tt_main ("tests" >::: tests)
I have spent literally the entire morning failing to get this to work.
I have tried to find out how to do it in all these places:
https://realworldocaml.org/v1/en/html/files-modules-and-programs.html
http://caml.inria.fr/pub/distrib/ocaml-4.01/ocaml-4.01-refman.html
https://ocaml.org/learn/tutorials/modules.html
...and several other places, and found nothing that looks even close to relevant to the problem (or that works).
Even though there are pages and pages of OCaml documentation out there, I cannot find anything that will tell me how to write the Mymod
module.
I have tried put any of the following in my mymod.mli
file:
let echo x = x ;;
let echo : string -> string = fun x -> x ;;
let echo x : string = x ;;
...along with several dozen other variants; they all fail to even compile, let alone pass the tests. The compiler error messages are impenetrable (e.g.: illegal begin of interf
), and I can find no documentation to interpret them.
Neither can I find in the documentation the syntax for defining a function that just returns its (string) input.
I'd appreciate some help.
Upvotes: 0
Views: 62
Reputation: 66823
To elaborate on what @camlspotter points out, you should have a mymod.mli
file like this:
val echo : string -> string
and a mymod.ml
file like this:
let echo s = s
You can compile and run like this:
$ ocamlopt -c mymod.mli
$ ocamlopt -c mymod.ml
$ echo 'Printf.printf "saw %s\n" (Mymod.echo "hello world")' > main.ml
$ ocamlopt -o main mymod.cmx main.ml
$ ./main
saw hello world
This is described in Section 2.5 of the OCaml manual.
Upvotes: 3
Reputation: 9040
Write your code in mymod.ml
, not mymod.mli
. *.ml
is for code and *.mli
is for interface.
Upvotes: 2