How to enumerate an enum/type in F#

前端 未结 7 1991
攒了一身酷
攒了一身酷 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:10

    Here is a complete example that prints information about any discriminated union. It shows how to get cases of the discriminated union and also how to get the fields (in case you needed them). The function prints type declaration of the given discriminated union:

    open System
    open Microsoft.FSharp.Reflection
    
    let printUnionInfo (typ:Type) = 
      printfn "type %s =" typ.Name
      // For all discriminated union cases
      for case in FSharpType.GetUnionCases(typ) do
        printf "  | %s" case.Name
        let flds = case.GetFields()
        // If there are any fields, print field infos
        if flds.Length > 0 then 
          // Concatenate names of types of the fields
          let args = String.concat " * " [ for fld in flds -> fld.PropertyType.Name ] 
          printf " of %s" args
        printfn ""    
    
    // Example
    printUnionInfo(typeof>)
    

提交回复
热议问题