问题
Right, so this is an odd problem that really took me by surprise. Basically, I'm working on a build system that gives you the option of running shell commands before and after the main build. To execute these commands I'm just using Sys.command
. The problem is that whenever I use that function it changes the order in which functions are called. For example:
Sys.command "echo 'Hi!'";
Printf.printf "second\n";
Sys.command "echo 'Bye!'"
outputs
Hi!
Bye!
second
from both the REPL and compiled executables. However, if I use any other function it seems to work fine. Interestingly, if I define a function to call Sys.command
it still executes in the wrong order. I've tested this on both 4.02.1 running on GNU/Linux and 4.01.0 in Cygwin and get the same behavior on both. As far as I am aware the ;
does not affect call order. Am I missing something here?
回答1:
You have a buffering problem.
Try this:
Sys.command "echo 'Hi!'";
Printf.printf "second\n%!";
Sys.command "echo 'Bye!'"
The %!
specifier says to flush the buffer at that point.
Because it's a mixed paradigm language (with side effects), OCaml expressions are executed in a predictable order. You can depend on this. If things seem to be executed out of order, there is something else going on.
(As a side comment, note that order of evaluation of parameters to a function is not constrained.)
来源:https://stackoverflow.com/questions/31216473/ocaml-function-calls-happening-in-wrong-order