2 people like it.

Check if value is a valid enum or flags combination

-

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
[<RequireQualifiedAccess>]
module Enum =

  let isDefined<'a, 'b when 'a : enum<'b>> (value:'a) =
    let (!<) = box >> unbox >> uint64
    let typ = typeof<'a>
    if typ.IsDefined(typeof<System.FlagsAttribute>, false) then
      ((!< value, System.Enum.GetValues(typ) |> unbox)
      ||> Array.fold (fun n v -> n &&& ~~~(!< v)) = 0UL)
    else System.Enum.IsDefined(typ, value)
Multiple items
type RequireQualifiedAccessAttribute =
  inherit Attribute
  new : unit -> RequireQualifiedAccessAttribute

Full name: Microsoft.FSharp.Core.RequireQualifiedAccessAttribute

--------------------
new : unit -> RequireQualifiedAccessAttribute
module Enum

from Script
val isDefined : value:'a -> bool (requires enum)

Full name: Script.Enum.isDefined
val enum : value:int32 -> 'U (requires enum)

Full name: Microsoft.FSharp.Core.Operators.enum
val value : 'a (requires enum)
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box
val unbox : value:obj -> 'T

Full name: Microsoft.FSharp.Core.Operators.unbox
Multiple items
val uint64 : value:'T -> uint64 (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.uint64

--------------------
type uint64 = System.UInt64

Full name: Microsoft.FSharp.Core.uint64
val typ : System.Type
val typeof<'T> : System.Type

Full name: Microsoft.FSharp.Core.Operators.typeof
System.Reflection.MemberInfo.IsDefined(attributeType: System.Type, inherit: bool) : bool
namespace System
Multiple items
type FlagsAttribute =
  inherit Attribute
  new : unit -> FlagsAttribute

Full name: System.FlagsAttribute

--------------------
System.FlagsAttribute() : unit
type Enum =
  member CompareTo : target:obj -> int
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member GetTypeCode : unit -> TypeCode
  member HasFlag : flag:Enum -> bool
  member ToString : unit -> string + 3 overloads
  static member Format : enumType:Type * value:obj * format:string -> string
  static member GetName : enumType:Type * value:obj -> string
  static member GetNames : enumType:Type -> string[]
  static member GetUnderlyingType : enumType:Type -> Type
  ...

Full name: System.Enum
System.Enum.GetValues(enumType: System.Type) : System.Array
module Array

from Microsoft.FSharp.Collections
val fold : folder:('State -> 'T -> 'State) -> state:'State -> array:'T [] -> 'State

Full name: Microsoft.FSharp.Collections.Array.fold
val n : uint64
val v : 'a (requires enum)
System.Enum.IsDefined(enumType: System.Type, value: obj) : bool

More information

Link:http://fssnip.net/4V
Posted:13 years ago
Author:Daniel Robinson
Tags: enumeration , enum