ocaml 中是否可以有一个 .ml
文件,该文件提供可从另一个文件使用的函数,但也可以用作独立程序?
让我用一个例子来澄清。在Python中,你可以这样做:
#This file is square.py
def my_square(i) :
print "square of %d is %d" % (i,i*i)
if __name__ == '__main__' :
my_square(10)
现在,我可以将上述内容作为独立程序运行:python square.py
,但我也可以通过说 import square
从另一个文件中包含它来访问square
函数。
如何(如果可能)在 ocaml 中执行此操作?
谢谢!
最佳答案
OCaml 的直译是:
let my_square x = x * x
let () =
if Sys.argv.(0) = "square" then
print_int (my_square 10)
OCaml 中没有神奇的 __main__
名称,但您可以模仿它。如果只是链接,该模块将提供 my_square
函数。但如果程序的名称为"square"
,它将打印my_square(10)
的结果。
关于module - ocaml 模块和程序位于同一文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192382/