【问题标题】:How to define module that exports a single function?如何定义导出单个函数的模块?
【发布时间】:2014-11-08 02:19:12
【问题描述】:

多年来我一直想学习OCaml,最近我终于决定去学习它,但是我第一次真正接触OCaml并不吉利......

我正在使用一组练习来学习它(这种方法对我使用其他语言效果很好)。每个练习都附带一个测试脚本。第一个测试脚本是这样的:

(* 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)

我已经字面意思花了整个上午都没有让这个工作。

我已经尝试在所有这些地方找出如何做到这一点:

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

...和其他几个地方,发现 没有 看起来甚至与问题密切相关(或有效)。

即使有几页 OCaml 文档,我也找不到任何可以告诉我如何编写 Mymod 模块的内容。

我已尝试将以下任何内容放入我的 mymod.mli 文件中:

let echo x = x ;;
let echo : string -> string = fun x -> x ;;
let echo x : string = x ;;

...以及其他几十种变体;他们甚至都无法编译,更不用说通过测试了。编译器错误消息难以理解(例如:illegal begin of interf),我找不到解释它们的文档。

我在文档中也找不到定义只返回其(字符串)输入的函数的语法。

我将不胜感激。

【问题讨论】:

    标签: testing module ocaml


    【解决方案1】:

    要详细说明@camlspotter 指出的内容,您应该有一个像这样的mymod.mli 文件:

    val echo : string -> string
    

    还有一个像这样的mymod.ml 文件:

    let echo s = s
    

    你可以这样编译和运行:

    $ 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
    

    这在Section 2.5 of the OCaml manual 中有描述。

    【讨论】:

      【解决方案2】:

      将您的代码写入mymod.ml,而不是mymod.mli*.ml 用于代码,*.mli 用于接口。

      【讨论】:

        猜你喜欢
        • 2018-07-07
        • 1970-01-01
        • 2021-12-23
        • 2017-06-13
        • 2016-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多