How to make an interactive program?

2020-04-14 08:18发布

I'm learning Ocaml and I need to create a program that can interact with the user in the following way:

Program: "Welcome!"
User: command1 arg1 arg2
program: "The answer is..."
User: command2 arg
program: "The answer is..."
User: exit

I need a scheme of the loop that make something like that

1条回答
相关推荐>>
2楼-- · 2020-04-14 08:51

Here's a loop that will read lines of input until it reaches end of file, or sees a line that says "exit".

let rec loop () =
    match read_line () with
    | "exit" -> ()
    | s -> Printf.printf "I saw %s\n%!" s; loop ()
    | exception End_of_file -> ()

To call this loop in a source file, something like this will work:

let () = loop ()

To try it out in the toplevel (OCaml REPL):

# loop ();;
查看更多
登录 后发表回答