我正在尝试比较列表中所有元素的颜色元组。如果它们具有相同的颜色,则返回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#引发错误:此值不是函数,无法应用。
答案 0 :(得分:1)
您可以将最后一条规则写为| 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)