f# - 如何在条件下断言元组

标签 f#

鉴于元组:

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

有没有一种很好的方法可以在不创建单独函数的情况下评估条件中的元组值?

最佳答案

fst 函数可以帮助你在这里。

Return the first element of a tuple



一个例子:
let tuple = (true, 1)
if fst tuple then
    //whatever

还有一个 snd 对于第二个元素。

另一种选择是使用 pattern matching :
let tuple = (true, 1)

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

printfn "%s" value

这可以让您匹配更复杂的场景,这是 F# 中非常强大的构造。看看 MSDN Documentation 中的元组模式举几个例子。

关于f# - 如何在条件下断言元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10638515/

相关文章:

multithreading - 帮我推理一下 F# 线程

list - F# 嵌套列表问题

F#、FParsec 和更新 UserState

arrays - 如何将二维数组传递给 F# 中的函数?

f# - 为什么 F# 不允许 C# 允许的多个属性?

F# 子类型可区分联合

f# - 使用不区分大小写的比较从集合中减去记录

sorting - 在 F# 中对元组内的值进行排序

f# - 执行时会是尾调用吗?

F# 管道运算符到索引器属性?