-->

在调用OCaml中其他文件功能(Calling functions in other files i

2019-10-22 03:12发布

我有一个具有一定长度的功能hello.ml:

let rec length l = 
    match l with
        [] -> 0
    | h::t -> 1 + length t ;;

使用该功能call.ml:

#use "hello.ml" ;; 

print_int (length [1;2;4;5;6;7]) ;;

在解释器模式(ocaml的),我可以使用ocaml call.ml得到的结果,但是当我试图用ocamlc或ocamlbuild编译它,我得到了编译错误。

File "call.ml", line 1, characters 0-1:
Error: Syntax error

那么,如何修改主叫方,被叫方,并建立命令编译代码到可执行文件?

Answer 1:

#use指令只能在顶层(解释)。 在编译的代码,你应该使用模块名称: Hello.length

我将展示如何从一个类Unix命令行构建程序。 你必须这样适应环境:

$ ocamlc -o call hello.ml call.ml
$ ./call
6


Answer 2:

hello.ml

let rec length l = 
    match l with
        [] -> 0
    | h::t -> 1 + length t ;;

call.ml

open Hello

let () = print_int (Hello.length [1;2;4;5;6;7]) ;;

建立

ocamlc -o h hello.ml call.ml   

要么

ocamlbuild call.native 


文章来源: Calling functions in other files in OCaml