你能帮我吗,我制作这个程序是为了从一些 .txt 文件中获取输出,如下所示:
约翰:3:英国
保罗:18:我们
#load "str.cma"
let f_test = "/home/test.txt" ;;
(*
Recursive Reading function
*)
let read_lines f_test : string list =
if Sys.file_exists (f_test) then
begin
let ic = open_in f_test in
try
let try_read () =
try Some (input_line ic)
with End_of_file -> None
in
let rec loop acc =
match try_read () with
| Some s -> loop (s :: acc)
| None -> close_in_noerr ic; List.rev acc
in
loop []
with
e -> close_in_noerr ic; []
end
else
[]
;;
(*Using Records*)
type user = {
name : string;
age : int;
country : string;
};;
(*
Function to separated info in list
*)
let rec splitinfo ?(sep=":") l =
match l with
| [] -> []
| x::xs -> (Str.split (Str.regexp ":") x)::splitinfo xs;;
(*
Function to get users position
*)
let get_user l:user =
let age = int_of_string (List.nth l 1) in
let user_name = List.nth l 0 in
{
name = user_name;
age = age ;
country = List.nth l 2;
};;
(*
Function to check some parameter is valid
*)
let par1 u: int =
if (u.age = 3) then
1
else
0;;
(*
Reporting function
*)
let report_statistics list_users =
let child = ref 0 in
let teenager = ref 0 in
let adult = ref 0 in
print_string (" ----- -- Stats -- ----- \n" ) ;
List.iter (
fun user_l -> (
match user_l with
| [] -> print_string("> no user <\n")
| _ ->
let user = get_user user_l in
if (par1 user = 1) then (
print_string (" "^ user.name ^" --> Child \n" ) ;
child := !child + 1;
)
else
print_string (" "^ user.name ^" --> Other \n" );
)
) list_users;
print_string ("------- List ---- ");
print_newline();
print_string ("Child " );
print_int(!child);
print_newline();
print_string ("Teenager ") ;
print_int(!teenager);
print_newline();
print_string ("Adult ");
print_int(!adult);
print_newline();
;;
程序编译但没有输出任何结果...
我错过了什么?
我保持检查参数的功能简单,这样我可以更好地理解它,但无法弄清楚为什么它不输出任何结果
你能帮我一下吗?
提前致谢:)
给出的代码定义了一些函数,例如
read_lines
和report_statistics
。但没有调用这些函数。
如果没有涉及其他 OCaml 源,这可能是您的问题。您需要调用这些函数。
通常有一个“主”函数来完成 OCaml 程序的工作,然后(这是关键)您必须实际调用主函数:
let main () =
(* Call the functions that do the work of the program *)
let () = main ()
我很多次忘记了最后一行,然后当我运行程序时什么也没有发生。