我目前正在尝试通过“Real World OCaml:面向大众的函数式编程”教科书来学习 OCaml。在 utop 中玩完后,我已经达到了尝试构建我的第一个可执行文件的地步,但程序一直以以下方式崩溃。代码本身与书中完全相同:
open Base
open Stdio
let rec read_and_accumulate accum =
let line = In_channel.input_line In_channel.stdin in
match line with
| None -> accum
| Some x -> read_and_accumulate (accum +. Float.of_string x)
let () =
printf "Total: %F\n" (read_and_accumulate 0.)
尝试使用沙丘构建并运行后的错误日志给出了
Fatal error: exception Invalid_argument("Float.of_string ")
Raised at Stdlib.invalid_arg in file "stdlib.ml", line 30, characters 20-45
Called from Dune__exe__Main.read_and_accumulate in file "bin/main.ml", line 8, characters 44-61
Called from Dune__exe__Main in file "bin/main.ml", line 11, characters 23-47
我承认我不太确定为什么
Float.of_string
似乎是这里问题的原因,因为当我测试它时它在utop内部工作得很好。
我应该补充一点,我在 Debian 上运行 OCaml 版本 4.13.1,并且安装了 Base 和 Stdio。我还可以添加下面的屏幕截图以供澄清:
正如评论中提到的,结束程序的正确方法是通过
Ctrl-D
,而不是按 Enter
两次,我的错。