我是Ocaml的新手,我遇到了一个简单的循环问题,这是我的代码:
open Str;;
let main () =
let quit_loop = ref false in
while not !quit_loop do
let str = read_line () in
if Str.string_match (Str.regexp "create") str 0
then let train_list = Str.split (Str.regexp "[ \t]+") str in
print_string "List created\n";
if Str.string_match (Str.regexp "delete") str 0
then let train_list = Str.split (Str.regexp "[ \t]+") str in
print_string "train deleted\n";
if Str.string_match (Str.regexp "quit") str 0
then quit_loop := true
done;;
let _ = main ()
代码编译但似乎只有“创建”工作。如果您有任何提示可以帮助我...
谢谢!
答案 0 :(得分:0)
如果你正确地缩进它,你就会得到这个:
open Str;;
let main () =
let quit_loop = ref false in
while not !quit_loop do
let str = read_line () in
if Str.string_match (Str.regexp "create") str 0
then let train_list = Str.split (Str.regexp "[ \t]+") str in
print_string "List created\n";
if Str.string_match (Str.regexp "delete") str 0
then let train_list = Str.split (Str.regexp "[ \t]+") str in
print_string "train deleted\n";
if Str.string_match (Str.regexp "quit") str 0
then quit_loop := true
done;;
let _ = main ()
如您所见,其他if
嵌套在第一个if
块中。这是因为let e = ... in instr1; ...
创建了一个包含随后所有内容的块。
你应该写(你可以用begin ... end
替换(...)
):
open Str;;
let main () =
let quit_loop = ref false in
while not !quit_loop do
let str = read_line () in
if Str.string_match (Str.regexp "create") str 0
then begin
let train_list = Str.split (Str.regexp "[ \t]+") str in
print_string "List created\n"
end;
if Str.string_match (Str.regexp "delete") str 0
then begin
let train_list = Str.split (Str.regexp "[ \t]+") str in
print_string "train deleted\n"
end;
if Str.string_match (Str.regexp "quit") str 0
then quit_loop := true
done;;
let _ = main ()
它将按预期工作。