module - ocaml 模块和程序位于同一文件中

标签 module ocaml

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/

相关文章:

python - 如何添加获取我使用 from x import * 导入的模块数组?

python - 捆绑方法包装器

python - 在 python 中运行特定的批处理命令

types - 如何在 OCaml 中定义两个相互链接的模块?

javascript - 如何在 Javascript 中使用 Babel 脚本的对象?

iOS 混合动态框架 - 将 objc header 与私有(private)模块桥接

arrays - 如何打印二维阵列

ocaml - Ocaml 库中的 string_dec 和字符串

f# - 如果 SML.NET 有仿函数,为什么 F# 不能?

ocaml - 我可以使用 OCamlBuild 生成可在没有 OCaml 库的计算机上运行的 native 可执行文件吗?