Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# bit flags enum

Tags:

f#

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?

like image 897
Rob Lyndon Avatar asked Sep 29 '16 13:09

Rob Lyndon


2 Answers

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
like image 121
marklam Avatar answered Nov 11 '22 21:11

marklam


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
like image 6
monoceres Avatar answered Nov 11 '22 21:11

monoceres