Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an interactive program?

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

like image 213
Gutimore Avatar asked Jul 29 '26 02:07

Gutimore


1 Answers

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 ();;
like image 87
Jeffrey Scofield Avatar answered Jul 30 '26 19:07

Jeffrey Scofield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!