【问题标题】:How to make an interactive program?如何制作互动节目?
【发布时间】:2017-09-02 05:00:13
【问题描述】:

我正在学习 Ocaml,我需要创建一个可以通过以下方式与用户交互的程序:

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

我需要一个循环的方案来制作类似的东西

【问题讨论】:

  • StackOverflow 在回答具体问题方面非常有效。但是您正在寻求更广泛的帮助。一般来说,你可以用"Printf.printf "string\n%!"写一个字符串,你可以用read_line ()读一行输入。
  • 如何构建主循环?
  • 我会写一个循环来回答你的问题。
  • ocamllex 也是一个很好的工具来做这样的事情:courses.softlab.ntua.gr/compilers/2015a/ocamllex-tutorial.pdf

标签: input functional-programming ocaml interactive


【解决方案1】:

这是一个循环,它将读取输入行直到它到达文件末尾,或者看到一行写着“退出”。

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

要在源文件中调用这个循环,可以这样:

let () = loop ()

在顶层尝试一下(OCaml REPL):

# loop ();;

【讨论】:

  • 这正是我正在寻找的答案!非常感谢!
  • 这个例子在OCaml documentation 中会很有趣,因为这是每个OCaml 新手都想做的基本事情。 :)
猜你喜欢
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2014-12-31
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多