'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> ()


Solution 1:[1]

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.

Solution 2:[2]

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" 

Solution 3:[3]

you need to refer to the app_name from your account.urls instead of 'main', and then use the name value of the corresponding url route. Reverse referencing for urls works for individual urls, not for the script. '<app_name>:<route_name>' - always use this format.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tranquillity
Solution 2 sdgfsdh
Solution 3 Rifat Rakib