为什么这个F#函数的参数值似乎变为0?

McM*_*ons 2 parameters f# matching

我正在尝试编写一个递归函数来构建一个专门的卡片组.第一个参数numOfCards应该是牌组中的牌数.sourceDeck是可用于构建套牌的可能卡的列表,currentDeck是我的累加器,这导致最终的卡列表.

但是,我遇到的问题是,当我为numOfCards发送一个数字值时,它会在match语句中设置为0.或者至少它看起来如何.我尝试使用调试器,当我输入函数时,值是正确的.然而,一旦我开始执行匹配,它突然变为0,如果我将鼠标悬停在匹配中的值和参数中的值(至少是一致的)上.

因此,匹配在0上触发,只返回空的currentDeck,而不是迭代.

关于这个的任何提示?可能是简单的事情,但我很难过.:)

let rec buildDungeon (numOfCards, sourceDeck : List<Card>, currentDeck : List<Card>) =
  match currentDeck.Length with
    | numOfCards  -> currentDeck
    | _           -> buildDungeon (numOfCards, sourceDeck, newCard(sourceDeck)::currentDeck)
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 5

如果你想处理一个currentDeck.Length 等于 的情况,numOfCards那么你需要写:

let rec buildDungeon (numOfCards, sourceDeck : List<Card>, currentDeck : List<Card>) =
  match currentDeck.Length with
  | n when n = numOfCards -> currentDeck
  | _ -> buildDungeon (numOfCards, sourceDeck, newCard(sourceDeck)::currentDeck)
Run Code Online (Sandbox Code Playgroud)

问题在于,当您编写子句时| numOfCards -> (...),模式匹配会将值绑定currentDeck.Length到符号numOfCards(并且新定义的numOfCards值会隐藏同名的先前值 - 即您获得的值作为参数).

我上面写的模式匹配绑定currentDeck.Length到一个符号n然后检查n = numOfCards(指向numOfCards传递的参数).

因此,模式匹配并不是检查相等性的最佳工具 - 您的代码可能更容易使用normal编写if:

let rec buildDungeon (numOfCards, sourceDeck : List<Card>, currentDeck : List<Card>) =
  if currentDeck.Length = numOfCards then currentDeck
  else buildDungeon (numOfCards, sourceDeck, newCard(sourceDeck)::currentDeck)
Run Code Online (Sandbox Code Playgroud)