如何检查列表是否包含带类型的可区分联合案例?

How to check if list contains discriminated union case with type?

给定以下代码:

type Creature = 
    { Strength: int 
      Toughness: int }

type CardType = 
    | Creature of Creature
    | Land 
    | Instant

type Card = 
    { Types: CardType list }
module Card = 
    let isType t card = List.contains t card.Types


我会写

Card.isType Land

在尝试检查卡片是否为生物时,出现以下错误:

This expression was expected to have type
    'CardType'    
but here has type
    'Creature -> CardType'

是否有这样的“isType”函数,或者我是否坚持在单独的“isCreature”函数上进行模式匹配?

除非你想求助于各种 reflection-based 技巧,否则你只能使用模式匹配。我可能会使用 List.exist 而不是 List.contains (采用谓词)来定义更通用的函数。然后您可以轻松地为您的特定卡片类型定义三个函数:

module Card = 
  let isType t card = 
    List.exists t card.Types
  
  let isCreature = 
    isType (function Creature _ -> true | _ -> false)
  let isLand = isType ((=) Land)
  let isInstant = isType ((=) Instant)

对于 LandInstant,您可以只检查该值是否等于您要查找的特定值。对于 Creature,这需要模式匹配 - 但可以使用 function.

很好地完成