Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

Does F# have the ternary ?: operator?

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

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

question from:https://stackoverflow.com/questions/28551938/does-f-have-the-ternary-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it's called if .. then .. else

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

In C# var x = true ? 0 : 1;

In F# let x = if true then 0 else 1

So in your case:

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

you can shorten it a bit with elif

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

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)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...