How to make an interactive program?

自闭症网瘾萝莉.ら 提交于 2019-12-04 04:44:56

问题


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:


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 ();;


来源:https://stackoverflow.com/questions/43267452/how-to-make-an-interactive-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!