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

发布于 2025-01-09 07:07:57 字数 564 浏览 0 评论 0原文

给出以下代码:

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”函数代替?

Given the follwing code:

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


I am able to write

Card.isType Land

When trying to check if card is a creature, i get the following error:

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

Is it even possible to have a "isType" function like this or am I stuck with pattern matching on a separate "isCreature" function instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

强者自强 2025-01-16 07:07:57

除非您想诉诸各种基于反射的技巧,否则您将不得不使用模式匹配。我可能会使用 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很好地完成。

Unless you want to resort to various reflection-based hacks, you are stuck with pattern matching. I would probably define a bit more general function using List.exist rather than List.contains (taking a predicate). Then you can easily define three functions for your specific card types:

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)

For Land and Instant, you can just check if the value equals the specific one you're looking for. For Creature, this requires pattern matching - but can be done quite nicely using function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文