Calling functions in other files in OCaml

落花浮王杯 提交于 2019-12-11 13:16:16

问题


I have hello.ml that has a length function:

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

call.ml that uses the function:

#use "hello.ml" ;; 

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

In interpreter mode (ocaml), I can use ocaml call.ml to get the results, but when I tried to compile it with ocamlc or ocamlbuild, I got compilation error.

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

Then, how to modify the caller, callee, and build command to compile the code into executables?


回答1:


The #use directive only works in the toplevel (the interpreter). In compiled code you should use the module name: Hello.length.

I'll show how to build the program from a Unix-like command line. You'll have to adapt this to your environment:

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



回答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]) ;;

Build

ocamlc -o h hello.ml call.ml   

or

ocamlbuild call.native 


来源:https://stackoverflow.com/questions/28756989/calling-functions-in-other-files-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!