简体   繁体   中英

How to define module that exports a single function?

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 (eg: 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.

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 .

Write your code in mymod.ml , not mymod.mli . *.ml is for code and *.mli is for interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM