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?
If you want to save the typing you can define your own
Note that you can't use : in operators so ?= is the nearest you can get.
Usage: maybe ?= ("true", "false")
You can also implement this using pattern matching with function using guards:
Pattern matches may seem longer ternary operator but they are much easier to read when logic gets more complex.
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:
you can shorten it a bit with
elif
Another option to consider in F# specially when you have more than 2 cases is pattern matching:
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#.For more examples of C# expressions and statements in F# you can refer to this page. For example:
Ternary operator
Switch statement