首页 > 解决方案 > 如何将列表的元组与值进行比较?

问题描述

我正在尝试比较列表中所有元素的颜色元组。如果它们具有相同的颜色,则返回 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# 抛出错误:此值不是函数,无法应用。

标签: if-statementdesign-patternstypesf#

解决方案


您可以将最后一条规则写为| 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)

推荐阅读