Reputation: 4027
I have an OCaml function that converts a string to an array. What is the canonical way of writing a "main" function to call this and print the array.
let createArray pattern patArray =
(* some unimportant way of setting all the elements in the array patArray
based on the string pattern *)
let main () =
let pattern = "Pattern" in
let patArray = Array.create (String.length pattern) 0 in
let res = createArray pattern patArray in
Array.iter ~f:(printf "%d ") patArray;; <------------------
main ()
1) In the above, if I leave out the ';;' , it does not work. What is the significance of that?
2) Instead of using a dummy binding "res" , can I somehow just write two statements to be executed sequentially , like so:
createArray pattern patArray
Array.iter ~f:(printf "%d ") patArray
Upvotes: 0
Views: 363
Reputation: 8730
Without the ;;
, the parser cannot know that the main ()
call following that line is supposed to be a stand-alone expression (whitespace is not significant here).
You can use the following idiom instead:
let main () = ...
let () = main ()
The let () = expr
idiom will evaluate an expression of type unit
at that point. The initial let
informs the parser that a new top-level let
construct begins. Using ;;
is an alternative way to tell the parser about the end of a top-level construct, but is primarily intended for interactive use.
In order to evaluate two expressions sequentially, separate them with a semicolon (use parentheses or begin ... end
if you're unsure about precedence rules). For example:
let patArray = Array.create (String.length pattern) 0 in
createArray pattern patArray;
Array.iter ~f:(printf "%d ") patArray
Or, using begin
and end
to make precedence clearer:
let patArray = Array.create (String.length pattern) 0 in begin
createArray pattern patArray;
Array.iter ~f:(printf "%d ") patArray
end
Without the ;
, the parser would not know whether Array.iter
on the next line is supposed to an additional argument to the createArray
call.
Upvotes: 2