fsharp 中受歧视工会的列表
有人能解释为什么下面的 2 个 let 语句不起作用吗?
type Rank =
| Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine
| Ten
type Face =
| Jack
| Queen
| King
| Ace
type Suit =
| Diamonds
| Clubs
| Hearts
| Spades
type Card =
| RankCard of Rank * Suit
| FaceCard of Face * Suit
let deck : Card = [ (Two, Diamonds); (Jack, Hearts) ]
该表达式应具有 Card 类型,但此处具有 'a list 类型
,此 let 给出的
let deck : Card list = [ (Two, Diamonds); (Jack, Hearts) ]
表达式应具有 Card 类型,但此处具有 'a * 'b 类型
Can anybody explain why following 2 let statements don't work?
type Rank =
| Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine
| Ten
type Face =
| Jack
| Queen
| King
| Ace
type Suit =
| Diamonds
| Clubs
| Hearts
| Spades
type Card =
| RankCard of Rank * Suit
| FaceCard of Face * Suit
let deck : Card = [ (Two, Diamonds); (Jack, Hearts) ]
This expression was expected to have type Card but here has type 'a list
and this let gives
let deck : Card list = [ (Two, Diamonds); (Jack, Hearts) ]
expression was expected to have type Card but here has type 'a * 'b
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
F# 是一种类型安全语言。因此第一个表达式是错误的,因为
Card
和'a list
不兼容。第二个表达式也不正确,因为您的注释需要Card
类型的列表元素,但您提供了元组。此外,
(Two, Diamonds)
和(Jack, Hearts)
在同一列表中使用甚至不合法。前者是Rank * Suit
的元组,后者是Face * Suit
的元组。您的意图是创建两个 Card 类型的值;您必须根据
Card
的不同联合情况提供适当的构造函数:现在您可以在同一列表
deck 中使用
,并且 F# 类型检查器将自动推断c1
和c2
deck
具有Card list
类型:或者,您有一个列表,如下所示:
F# is a type-safe language. So the first expression is wrong since
Card
and'a list
are incompatible. The second expression is also incorrect because your annotation requires list elements inCard
type but you provided tuples instead.Moreover,
(Two, Diamonds)
and(Jack, Hearts)
are not even legal to use in the same list. The former is a tuple ofRank * Suit
and the latter is a tuple ofFace * Suit
.Your intention is creating two values of type
Card
; you have to provide appropriate constructors based on different union cases ofCard
:Now you can use
c1
andc2
in the same listdeck
, and F# type checker will automatically inferdeck
to have the type ofCard list
:Alternatively, you have a list as follows:
您需要使用
RankCard
或FaceCard
构造函数 - 否则 F# 认为您刚刚给了它一个正常的元组列表。或者,为什么不让 F# 自行推断类型呢?
You need to use the
RankCard
orFaceCard
constructor -- otherwise F# thinks you've just given it a normal list of tuples.Alternatively, why not let F# infer the types itself?