2016-09-29 160 views
3

我想在F#中創建一個位標記枚舉,使用bitshift操作符來提高可讀性:例如,F#位標誌枚舉

[<Flags>] 
type DaysOfWeek = 
    | Monday = 1 <<< 0 
    | Tuesday = 1 <<< 1 
    | Wednesday = 1 <<< 2 
    | Thursday = 1 <<< 3 
    | Friday = 1 <<< 4 
    | Saturday = 1 <<< 5 
    | Sunday = 1 <<< 6 

但是,F#編譯器不喜歡這個。它說「成員定義中的意外中綴運算符」。

我寧願這種方法超過兩個手動權力。有沒有辦法讓編譯器說服我不是邪惡的?

回答

6

這不正是你問什麼,但你可以使用0b前綴寫二進制速記,例如:

[<Flags>] 
type DaysOfWeek = 
    | Monday = 0b0000001 
    | Tuesday = 0b0000010 
    | Wednesday = 0b0000100 
    | Thursday = 0b0001000 
    | Friday = 0b0010000 
    | Saturday = 0b0100000 
    | Sunday = 0b1000000 
+0

對我來說夠好。 –

3

用於分隔值,更詳細的但更靈活的情況下,替代的方法:

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