F# 是否有三元 ?: 运算符? [英] Does F# have the ternary ?: operator?

查看:23
本文介绍了F# 是否有三元 ?: 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 C# 学习 F#,我刚刚尝试编译一个像

I'm learning F# coming from C# and I've just tried compiling an expression like

let y = Seq.groupBy (fun x -> (x < p ? -1 : x == p ? 0: 1))

但请参阅表达式中的意外整数文字".F# 有三元运算符吗?如果没有,我应该用什么代替?

but see 'unexpected integer literal in expression'. Does F# have a ternary operator? If not, what should I use instead?

推荐答案

是的,它叫做 if .. then .. else

事实上,在 F# 中,一切都是表达式,甚至是 if .. then .. else 块.

In fact in F# everything is an expression, even an if .. then .. else block.

在 C# 中 var x = true ?0 : 1;

在 F# 中 let x = if true then 0 else 1

所以在你的情况下:

let y = Seq.groupBy (fun x -> if x < p then -1 else if x = p then 0 else 1)

你可以用 elif

let y = Seq.groupBy (fun x -> if x < p then -1 elif x = p then 0 else 1)

当您有超过 2 种情况时,在 F# 中要特别考虑的另一个选项是模式匹配:

Another option to consider in F# specially when you have more than 2 cases is pattern matching:

let f p x =
    match x with
    | x when x < p -> -1
    | x when x = p ->  0
    | _ -> 1

let y = Seq.groupBy (f p)

但在您的特定情况下,我会使用 if .. then .. elif .. then.

But in your particular case I would use the if .. then .. elif .. then.

最后注意测试相等运算符是 = 而不是 C# 中的 ==.

Finally note that the test-equality operator is = not == as in C#.

这篇关于F# 是否有三元 ?: 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆