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

查看:78
本文介绍了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 =如果为true,则为0,否则为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)

在两种情况下特别要在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天全站免登陆