如何在条件语句中断言一个元组

3

给定元组:

let tuple = (true, 1)

我该如何在条件语句中使用元组? 类似于这样:
if tuple.first then //doesnt work

或者

if x,_ = tuple then // doesnt work

我不想做这件事:

let isTrue value = 
   let b,_ = value
   b

if isTrue tuple then // boring

有没有一种好的方法在条件语句中评估元组值,而不需要创建单独的函数?

3个回答

7

这里可以使用 fst 函数来帮助你。

返回元组的第一个元素。

例如:

let tuple = (true, 1)
if fst tuple then
    //whatever

还有第二个元素的snd

另一个选择是使用模式匹配

let tuple = (true, 1)

let value = 
    match tuple with
    | (true, _) -> "fst is True"
    | (false, _) -> "fst is False"

printfn "%s" value

这可以让您在更复杂的情况下进行匹配,是F#中非常强大的结构。请查看MSDN文档中的元组模式以获取一些示例。


3
您要查找的函数名是"fst"。
let v = (true, 3)
if fst v then "yes" else "no"

"fst"将获得元组的第一半。 "snd"将获取第二半。

如需更多信息,请参阅MSDN此处的信息


2
你可以使用 fst 函数:
if tuple |> fst then
    ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接