How to enumerate an enum/type in F#

前端 未结 7 2112
攒了一身酷
攒了一身酷 2021-01-11 09:43

I\'ve got an enumeration type defined like so:

type tags = 
    | ART  = 0
    | N    = 1
    | V    = 2 
    | P    = 3
    | NULL = 4

is

7条回答
  •  旧巷少年郎
    2021-01-11 10:08

    You can use Enum.GetValues, which returns an Array of objects that you then have to downcast to integer values. (Note: I'm using Mono's F# implementation; maybe things are different with .NET.)

    Here are some functions I wrote to get a list of all enumeration values and to get the min and max values:

    open System
    
    module EnumUtil =
    
        /// Return all values for an enumeration type
        let EnumValues (enumType : Type) : int list =
            let values = Enum.GetValues enumType
            let lb = values.GetLowerBound 0
            let ub = values.GetUpperBound 0
            [lb .. ub] |> List.map (fun i -> values.GetValue i :?> int) 
    
        /// Return minimum and maximum values for an enumeration type
        let EnumValueRange (enumType : Type) : int * int =
            let values = EnumValues enumType
            (List.min values), (List.max values)
    

提交回复
热议问题