我在控制台上有一个整数列表(我不知道有多少个),
3
10
9
8
2
7
5
1
3
0
我想将它们读入列表中,并按读入时的顺序将它们打印回去。到目前为止,我已经尝试了以下方法,但是它不起作用。
let rec read_nums arr = (*takes an initial array*)
try
let i = read_int () in (*read next integer*)
read_nums (i::arr) (*append to array and recurse*)
with End_of_file -> arr (*return array if everything has been read*)
let input = (read_nums []) (*call the function*)
(*destruct the list, print head, recurse*)
let rec print_input array = match arr with
| hd::tl -> (print_int hd; print_input tl;)
| [] -> ()
(*call the function*)
print_input input
失败,并出现以下错误
File "solution.ml", line 15, characters 12-17:
Error: Syntax error
答案 0 :(得分:3)
在顶级表达式之前添加let () = ...
。
您的语法错误来自最后一行:
let rec print_input arr =
match arr with
| hd::tl -> (print_int hd; print_input tl)
| [] -> ()
print_input input (* this line! *)
在这里,看起来print_input input
是顶层的函数应用程序,但是,它也可以是构造函数应用程序() print_input
,如下所示:
let rec print_input arr =
match arr with
| hd::tl -> (print_int hd; print_input tl)
| [] -> () print_input input
粗略地说,OCaml解析器首先认为它是构造函数应用程序,但随后input
仍然保持单独状态,因此会发生错误。
为避免这种情况,您可以使用let () = ...
:
let rec print_input arr =
match arr with
| hd::tl -> (print_int hd; print_input tl)
| [] -> ()
let () =
print_input input
使用此约定,所有顶级表达式都会消失。另外,由于它要求返回的表达式的类型为unit
,因此这使我们的程序更安全。
有关详细信息,请参阅此OCaml教程:The Structure of OCaml Programs
答案 1 :(得分:1)
将来:
关于错误:似乎OCaml的let
绑定具有形式let ... in expr
。以下作品:
let rec read_nums arr = (*takes an initial array*)
try
let i = read_int () in (*read next integer*)
read_nums (i::arr) (*append to array and recurse*)
with End_of_file -> arr (*return array if everything has been read*)
in
let input = (read_nums [1; 2]) in (*call the function*)
(*destruct the list, print head, recurse*)
let rec print_input arr = match arr with
| hd::tl -> (print_int hd; print_input tl;)
| [] -> ()
in
print_input input