Search code examples
ocamlscriptedmain

Scripted main in OCaml?


How can I emulate this Python idiom in OCaml?

if __name__=="__main__":
   main()

See RosettaCode for examples in other programming languages.


Solution

  • $ 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:

    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 -> ()
    

    Posted on RosettaCode.