list - 预定义列表 F# 的总和

标签 list recursion f# sum blackjack

我是一名 F# 初学者,目前正在尝试 BlackJack F# 实现中的一些列表操作。

我正在尝试对我创建的列表的元素进行求和,如下所示:

let cardsvalue (k: Cards): List<int> =
    match k with
    |Ace ->  [1;11]
    |Two -> [2] 
    |Three -> [3]
    |Four -> [4]
    |Five -> [5]
    |Six -> [6]
    |Seven -> [7]
    |Eight -> [8]
    |Nine -> [9]
    |Ten | Jack | Queen | King -> [10] 

type Cards 只是纸牌 2 到 9、10 到 King 和 Ace 的并集。

所以我需要某种递归函数 CardPoints,它只需从 cardsvalue 添加项目,例如 [Two;三] = [5][Ace;高手;艾斯] = [3; 13; 23; 33] 表示 Ace 的所有可能值。我尝试了几种常见的求和方法,但最终总是出现类型不匹配或不支持运算符错误。例如

let rec CardPoints (cp: List<Cards>): List<int> =   
   match cp with
   | head :: tail -> head + CardPoints tail
   | [] -> 0 

它不接受 + 运算符。

我很想看到这个问题的可能实现。感谢您的宝贵时间!

最佳答案

I am a beginner F# learner

您的代码显示了一种很好的系统方法,并且您已经完成了大部分工作,以允许类型系统(和智能感知)帮助解决您的问题。

let cardsvalue (k: Cards): List<int> =

一个有用的函数,具有完全正确的类型签名。请注意,它呈灰色。这意味着您没有使用它。

let rec CardPoints (cp: List<Cards>): List<int> =

也完全正确。您正在为类型系统提供尽可能多的帮助,这使得它几乎可以肯定它会发现出现问题的确切点。

I always end up with type mismatch or not supporting operator error. For example

    | head :: tail -> head + CardPoints tail

尝试使用绑定(bind)来帮助解决这个问题:

    | head :: tail ->
        let tailPoints = CardPoints tail
        head + tailPoints

您可以(将鼠标悬停在它们上方)知道 headCardstailPointsList<int> 。所以你正在尝试添加 CardsList<int>并且没有定义这样的加法运算。

因此,您将其细化为一个较小的任务:给定一张牌( head: Cards ),并给出剩余牌中可能的分数( tailPoints: List<int> ),如何从所有牌中找到可能的分数,这应该是 List<int> ?您将需要使用当前未使用的功能 cardsvalue再迈出一小步,你就到了。

关于list - 预定义列表 F# 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65382271/

相关文章:

c# - WPF - 将数据库值添加到 List<class>

r - 组合 R 中的列表元素

python - dict 追加键和值的列表

f# - Erlang 替代 f# 序列

f# - 异步数据库查询

performance - F# 处理复杂键(如数据结构中的 int*int*int)比 Ocaml 慢得多

c# 从父类访问子类

javascript - 获取树列表的级别 - JavaScript

algorithm - 如何从递归算法中找到递归关系

c++ - 带 *& 参数的递归 void 函数