Ocaml 标准输入接口

Ocaml stdin interface

我需要使用 ocaml 处理来自标准输入的用户输入。用户将输入命令,直到他键入 quit 然后程序结束。这该怎么做?我知道如何使用命令式编程,但我想学习函数式编程。用户应该根据他的命令操作堆栈中的数据。我也想像解析器一样处理用户命令。

非常感谢您的帮助!

这是您可以使用 OCaml 堆栈库编写的内容的草图。它远非完美,可以在很多方面进行改进,但这里是一般结构。

就您的问题而言,最重要的部分是 loop 函数。它从标准输入中读取一行,并使用模式匹配来结束程序,或评估给定的命令,并递归调用自身以等待另一个命令。

eval 函数使用给定参数的模式匹配来做正确的事情。您可以找到 Stack 模块 here.

的文档
let stack = Stack.create ()

let eval args =
  match args with
  | ["push"; v] -> Stack.push v stack
  | ["pop"] -> begin try print_endline (Stack.pop stack) with
      | Stack.Empty -> print_endline "Stack is empty"
    end
  | ["show"] -> Stack.iter print_endline stack
  | _ -> print_endline "Unrecognized command"

let rec loop () =
  match read_line () with
  | "quit" -> print_endline "Bye"
  | _ as command -> eval (String.split_on_char ' ' command); loop ()


let () =
  loop ()

注意:我通常不太喜欢为一个没有大量研究的问题提供完整解决方案的想法,但是嘿,你必须当您不熟悉函数式编程时从某个地方开始。

注 2:此代码仅适用于 string 个堆栈。如果你打算存储不同的类型,比如 ints,或者如果你希望它是多态的,你需要稍微调整一下代码。

编辑:根据评论中的评论,下面是上述代码的改进版本,不使用全局变量堆栈。

let eval s args =
  match args with
  | ["push"; v] -> Stack.push v s
  | ["pop"] -> begin try print_endline (Stack.pop s) with
      | Stack.Empty -> print_endline "Stack is empty"
    end
  | ["show"] -> Stack.iter print_endline s
  | _ -> print_endline "Unrecognized command"

let rec loop s =
  match read_line () with
  | "quit" -> print_endline "Bye"
  | _ as command -> eval s (String.split_on_char ' ' command); loop s


let () =
  loop (Stack.create ())