如何检查列表是否包含具有类型的可区分联合案例?
给出以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非您想诉诸各种基于反射的技巧,否则您将不得不使用模式匹配。我可能会使用
List.exist
而不是List.contains
(采用谓词)定义更通用的函数。然后,您可以轻松地为您的特定卡类型定义三个函数:对于
Land
和Instant
,您只需检查该值是否等于您要查找的特定值即可。对于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 thanList.contains
(taking a predicate). Then you can easily define three functions for your specific card types:For
Land
andInstant
, you can just check if the value equals the specific one you're looking for. ForCreature
, this requires pattern matching - but can be done quite nicely usingfunction
.