有没有办法使用函数式编程避免 OCaml 中的循环?

Is there a way to avoid loops in OCaml using functional programming?

我正在尝试编写纸牌游戏,有时会询问用户:

"Submit the player's name or EXIT to start the game"

因此,在用户提交 "EXIT" 之前,我需要问这个问题,有人告诉我有一种不使用循环的方法可以做到这一点。

到目前为止我只有:

printf("Ingrese el nombre del jugador o EXIT para comenzar el juego");;
print_newline;;
let command = read_line;;

然后我会使用一个循环:

while (command <> "EXIT") do

但是被告知在做函数式编程时不好

非常感谢您。

只需使用一个在命令为 "EXIT" 时终止的递归函数。

这是一个函数,它从 stdin 读取文本行,直到它看到包含单词 EXIT 的行(或文件末尾):

let rec read_until_exit () =
    match
        try Some (read_line ())
        with End_of_file -> None
    with
    | None -> ()
    | Some s -> 
        if s = "EXIT" then ()
        else
            begin
            do_something_you_want_to_do_here_with_the_line s;
            read_until_exit ()
            end

为了让 Jeffrey 的回答更漂亮一点:

let rec read_until_exit () =
  match read_line () with
  | exception End_of_file -> ()
  | "EXIT" -> ()
  | s ->
    do_something_you_want_to_do_here_with_the_line s;
    read_until_exit ()