F# - 从选项类型函数获取元组的第一个元素
F# - Getting fst element of tuple from option type function
我正在尝试访问元组的第一个元素。一般我都是用fst(元组),但是这个情况有点不一样。
let getCard (pl : player) : (card * player) option =
let plDeck = pl
match plDeck with
| c1::re -> Some (c1,(re))
| [] -> None
这是我的 f# 代码。播放器类型是 ints
的列表,输出是播放器列表的第一个 int
和播放器列表减去第一个 int
.
的元组
这是我的计算机科学作业class,所以要求我使用选项类型。
我正在尝试通过编写
访问另一个函数中元组的 fst
元素
let gc = fst (getCard [1,2,3])
但我似乎不能这样做,因为我收到了警告:
This expression was expected to have type
''a * 'b' but here has type
'(card * player) option'
我该如何解决这个问题?
编译器告诉您,您正在尝试访问元组 card * player 的选项,而函数 fst 需要 card * player 的元组。
您可以在 getCard 函数上进行模式匹配并提取卡片。
let result =
match getCard [1..5] with
| Some card -> fst(card)
| None -> -1
您还可以使用模式匹配来提取元组的第一部分。
let result =
match getCard [1..5] with
| Some (card, _) -> card
| None -> -1
正如@Guran 所建议的,你不应该return 幻数
let result =
match getCard [1..5] with
| Some (card, _) -> Some card
| None -> None
我正在尝试访问元组的第一个元素。一般我都是用fst(元组),但是这个情况有点不一样。
let getCard (pl : player) : (card * player) option =
let plDeck = pl
match plDeck with
| c1::re -> Some (c1,(re))
| [] -> None
这是我的 f# 代码。播放器类型是 ints
的列表,输出是播放器列表的第一个 int
和播放器列表减去第一个 int
.
这是我的计算机科学作业class,所以要求我使用选项类型。
我正在尝试通过编写
访问另一个函数中元组的fst
元素
let gc = fst (getCard [1,2,3])
但我似乎不能这样做,因为我收到了警告:
This expression was expected to have type ''a * 'b' but here has type '(card * player) option'
我该如何解决这个问题?
编译器告诉您,您正在尝试访问元组 card * player 的选项,而函数 fst 需要 card * player 的元组。
您可以在 getCard 函数上进行模式匹配并提取卡片。
let result =
match getCard [1..5] with
| Some card -> fst(card)
| None -> -1
您还可以使用模式匹配来提取元组的第一部分。
let result =
match getCard [1..5] with
| Some (card, _) -> card
| None -> -1
正如@Guran 所建议的,你不应该return 幻数
let result =
match getCard [1..5] with
| Some (card, _) -> Some card
| None -> None