用于纸牌游戏的 OCaml rec 函数

OCaml rec function for a card game

我是函数式编程的新手,需要制作一个简单的纸牌游戏,但在记录功能方面遇到了麻烦。

假设我有一个包含 5 个玩家的列表。现在我用玩家当前的手为回合中的每个玩家打印一个菜单,然后玩家放下一张牌并绘制一张新牌。

我需要 运行 直到牌组中没有牌。

这是我的代码:

let rec round deck players =
  match deck with
    | [] -> ()
    | h::t -> (match players with
                  | x::xs -> print_mazo deck;
                    print_play x;
                    let i = read_int () in
                    let (newhand, carta) = drop x.mano i in
                    let (newdeck, newhand2) = draw deck newhand 1 in
                    print_ronda x carta;
                    round newdeck xs
                  | [] -> round newdeck players 
            )

我收到这个错误:

Error: Unbound value newdeck

我认为您的直接问题是:

let i = read_int

但你需要

let i = read_int ()

read_int 本身就是一个函数,它在 OCaml(和任何 FP 语言)中是一个相当普通的值。所以将 i 绑定到这个值不是错误。但是,编译器注意到该值没有正确的类型,即 int。您实际上想要 调用 函数;即,您需要将其应用于输入值。在 read_int 的情况下,它始终采用相同的输入值,().

浏览您的其余代码,我没有看到值 t 的任何用途。我怀疑还有一些工作要做才能完成玩家列表。

实际上,您的代码很奇怪。让我向您解释原因:

let rec round deck players =
match deck with
  | [] -> ()
  | h::t -> (match players with
              | x::xs -> (* Some code *)
                let (newdeck, newhand2) = draw deck newhand 1 in
                round newdeck xs (* good recursive call *)
              | [] -> round newdeck players (* bad recursive call *)
        )

为什么是 bad recursive call?因为您在模式匹配的第一个分支中声明了 newdeck 而不是在第二个分支中。所以,当你写 | [] -> round newdeck players 时,newdeck 来自哪里?

就像写作

let f x = let a = 3 in x + a
let y = a

您是否同意这个 af 本地的事实?如果您同意,这与您的 newdeck 位于模式匹配的第一个分支的本地相同。