if-statement - 如何将列表的元组与值进行比较?
问题描述
我正在尝试比较列表中所有元素的颜色元组。如果它们具有相同的颜色,则返回 true。如果不返回false。当我运行代码时,编译器会抛出错误。
我使用了模式匹配和嵌套 if 语句来检查列表头部的颜色是否与所有其他元素匹配。
type Suit = Clubs | Diamonds | Hearts | Spades
type Rank = Jack | Queen | King | Ace | Num of int
type Card = Rank * Suit
type Color = Red | Black
type Move = Discard of Card | Draw
let cards = [(Jack,Clubs); (Num(8),Spades)]
let card_color (c:Card) =
match c with
| _, Clubs -> Black
| _, Spades -> Black
| _, Diamonds -> Red
| _, Hearts -> Red
let all_same_color cs =
match cs with
| [] -> true
| x::xs ->
if not card_color cs.Head = card_color x then false else true
all_same_color cards
如果 head 与其他元素的颜色匹配,我希望它返回 true,否则返回 false。F# 抛出错误:此值不是函数,无法应用。
解决方案
您可以将最后一条规则写为| x::xs -> card_color cs.Head = card_color x
但我建议将 all_same_color 函数编写为
let all_same_color cs =
cs |> List.forall (fun x -> card_color x = card_color cs.Head)
推荐阅读
- c++ - C++ enable_shared_from_this 可以私有继承吗?
- kubernetes - 检查特性门是否在 kubernetes 中启用/禁用
- python - 如何使用fuzzywuzzy 的process.extract 函数按特定属性处理对象列表?
- c# - 从 ASP.NET MVC 中的类获取当前 ApplicationUser
- javascript - React Native:手机号码验证仅接受数值
- javascript - 如何使用按钮在我的 HTML 中实现 JavaScript 函数?
- mysql - 如何在现有列中添加值?
- distributed-database - 为什么启动 PD 时会显示 `etcd cluster ID mismatch` 消息?
- javascript - 蓝图/反应:滑块的自定义标签
- c - pthread_join() 后指向 int 的指针导致崩溃