Does F# have the ternary ?: operator?

后端 未结 4 1618
孤独总比滥情好
孤独总比滥情好 2021-01-07 16:04

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))
         


        
4条回答
  •  天涯浪人
    2021-01-07 16:43

    For more examples of C# expressions and statements in F# you can refer to this page. For example:

    Ternary operator

    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.)

    Switch statement

    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
    

提交回复
热议问题