问题描述
对,所以这是一个奇怪的问题,确实让我感到惊讶.基本上,我正在构建一个构建系统,该系统可让您选择在主构建之前和之后运行shell命令.要执行这些命令,我只是使用Sys.command
.问题是,每当我使用该函数时,它都会更改函数的调用顺序.例如:
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!'"
输出
Hi!
Bye!
second
来自REPL和已编译的可执行文件.但是,如果我使用任何其他功能,它似乎都可以正常工作.有趣的是,如果我定义了一个调用Sys.command
的函数,它仍然会以错误的顺序执行.我已经在运行GNU/Linux的4.02.1和Cygwin的4.01.0上对此进行了测试,并且在两者上都得到了相同的行为.据我所知,;
不会影响通话顺序.我在这里想念什么吗?
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?
推荐答案
您有缓冲问题.
尝试一下:
Sys.command "echo 'Hi!'";
Printf.printf "second\n%!";
Sys.command "echo 'Bye!'"
%!
说明符表示要在那一点上刷新缓冲区.
The %!
specifier says to flush the buffer at that point.
由于它是一种混合范例语言(具有副作用),因此OCaml表达式以可预测的顺序执行.您可以依靠它.如果事情似乎无法按顺序执行,那么还有其他事情发生.
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.)
这篇关于OCaml函数调用顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!