F# 有三元 ?: 运算符吗?

Does F# have the ternary ?: operator?

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

这样的表达式
let y = Seq.groupBy (fun x -> (x < p ? -1 : x == p ? 0: 1))

但请参阅 'unexpected integer literal in expression'。 F# 有三元运算符吗?如果没有,我应该用什么来代替?

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

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

在 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# 中特别要考虑的另一个选项是模式匹配:

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.

最后请注意,test-equality 运算符是 = 而不是 C# 中的 ==

您还可以使用模式匹配和使用守卫的函数来实现:

    let y = Seq.groupBy  (function |x when x < p -> -1
                                   |x when x = p -> 0
                                   |_ -> 1)

模式匹配可能看起来更长的三元运算符,但当逻辑变得更复杂时它们更容易阅读。

有关 F# 中的 C# 表达式和语句的更多示例,您可以参考 this 页面。例如:

三元运算符

C# has the ternary operator "?:" for conditional expressions:

condition ? trueVal : falseVal 

F# has the same operator, but its name is if-then-else:

if condition then trueVal else falseVal

(Note that "if" is used much less frequently in F# than in C#; in F#, many conditionalexpressions are done via pattern-matching rather than if-then-else.)

切换语句

C# has a switch statement. It looks something like this:

switch (x) 
{ 
    case 1: 
        SomeCode(); 
        break; 
    default: 
        SomeCode(); 
        break; 
} 

In F#, this is just one of many things that pattern matching expresses more succinctly:

    match x with 
     | 1 -> SomeCode() 
     | _ -> SomeCode()  // _ is a ‘catch all’ default

如果您想保存输入,您可以定义自己的输入

let (?=) (q: bool) (yes: 'a, no: 'a) = if q then yes else no

请注意,您不能在运算符中使用 :,所以 ?= 是您可以获得的最接近的值。

用法:也许?= ("true", "false")