我想从文件中读取一些数字,将它们带到列表中,最后在屏幕上显示它们.数字.txt目前已2 3 5 7 11作为输出我得到11 7 5 3 2 - : unit = ()
为什么会这样?
let rec int_list_from_sb sb n =
match n with
| 0 -> [];
| _ -> (bscanf sb " %d" (fun a -> a))::(int_list_from_sb sb (n - 1));;
let file_name = open_in "numbers.txt" in
let sb = Scanning.from_channel file_name in
let int_list = int_list_from_sb sb 5 in
List.iter (fun a -> print_int a) int_list;;
Run Code Online (Sandbox Code Playgroud)
在OCaml中未指定参数的评估顺序.所以,当你这样做f x :: g y,这是不确定是否f还是g被先叫.在你的情况下,在调用之前调用递归调用bscanf,这就是为什么你得到错误顺序的结果.
修复评估顺序问题的一般方法是在副作用的顺序很重要时将函数的参数放入局部变量中.因此f x :: g y,let fx = f x in fx :: g y如果您希望在调用f x之前发生影响,那么您可以这样做g.
但是在你的情况下,你可以bscanf像这样使用延续参数:
bscanf sb " %d" (fun a -> a :: int_list_from_sb sb (n - 1))
Run Code Online (Sandbox Code Playgroud)