I would like to create a bitflags enum in F#, using bitshift operators for readability: e.g.
[<Flags>]
type DaysOfWeek =
| Monday = 1 <<< 0
| Tuesday = 1 <<< 1
| Wednesday = 1 <<< 2
| Thursday = 1 <<< 3
| Friday = 1 <<< 4
| Saturday = 1 <<< 5
| Sunday = 1 <<< 6
However, the F# compiler dislikes this. It says "unexpected infix operator in member definition".
I would prefer this approach over manual powers of two. Is there a way to convince the compiler that I'm not being evil?
It's not exactly what you asked for, but you can write the binary longhand using the 0b
prefix, eg:
[<Flags>]
type DaysOfWeek =
| Monday = 0b0000001
| Tuesday = 0b0000010
| Wednesday = 0b0000100
| Thursday = 0b0001000
| Friday = 0b0010000
| Saturday = 0b0100000
| Sunday = 0b1000000
Alternative way that separates the cases from the values, more verbose but more flexible:
type DaysOfWeek =
| Monday
| Tuesday
| Wednesday
| Thursday
| Friday
| Saturday
| Sunday
with
static member Flag x =
let bit n = 1 <<< n
match x with
| Monday -> bit 0
| Tuesday -> bit 1
| Wednesday -> bit 2
| Thursday -> bit 3
| Friday -> bit 4
| Saturday -> bit 5
| Sunday -> bit 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With