简体   繁体   中英

F# check if generic type parameter is discriminated union

How to specify the type of discriminated union when creating a constraint? What should I write instead of DiscriminatedUnion ?

let f<'U when 'U :> DiscriminatedUnion> ()

I don't believe there is any way to enforce this check at compile time. At runtime you could use FSharpType.IsUnion ref in your implementation and handle the false case possibly by throwing an exception.

You can do this at compile-time for DUs that are compiled as enums:

let foo<'t when 't : enum<int>> (t : 't) =
  string t

type Fruit =
  | Apple = 0
  | Banana = 1
  | Cherry = 2

foo Fruit.Apple |> printfn "%s"

// Compile-time error
foo "abc" |> printfn "%s"

However, DUs compiled as classes will not satisfy this constraint:

type Shape =
  | Square of int
  | Rectangle of int * int

// Compile-time error
foo (Square 2) |> printfn "%s" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM