OCaml中的脚本主脚本? [英] Scripted main in OCaml?

查看:81
本文介绍了OCaml中的脚本主脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在OCaml中模拟此Python习惯用法?

How can I emulate this Python idiom in OCaml?

if __name__=="__main__":
   main()

有关其他编程语言的示例,请参见 RosettaCode .

See RosettaCode for examples in other programming languages.

推荐答案

$ ocamlc -o scriptedmain -linkall str.cma scriptedmain.ml
$ ./scriptedmain
Main: The meaning of life is 42
$ ocamlc -o test -linkall str.cma scriptedmain.ml test.ml
$ ./test
Test: The meaning of life is 42

scriptedmain.ml:

scriptedmain.ml:

let meaning_of_life : int = 42

let main () = print_endline ("Main: The meaning of life is " ^ string_of_int meaning_of_life)

let _ =
    let program = Sys.argv.(0)
    and re = Str.regexp "scriptedmain" in
        try let _ = Str.search_forward re program 0 in
            main ()
        with Not_found -> ()

test.ml:

let main () = print_endline ("Test: The meaning of life is " ^ string_of_int Scriptedmain.meaning_of_life)

let _ =
    let program = Sys.argv.(0)
    and re = Str.regexp "test" in
        try let _ = Str.search_forward re program 0 in
            main ()
        with Not_found -> ()

发布在 RosettaCode 中.

这篇关于OCaml中的脚本主脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆