【问题标题】:How do I compare tuples of a list with a value?如何将列表的元组与值进行比较?
【发布时间】:2019-05-19 19:07:27
【问题描述】:

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

【问题讨论】:

  • Error is one line 21 --> if not card_color cs.Head = card_color x then false else true

标签: if-statement design-patterns types f#


【解决方案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)

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多