Test Pattern Match Type for DU

With DU (discriminatory union types), how do I match a test type pattern? I have the following code:

type IU =
|Int of int
|Unit of Unit

let x = IU.Int(3)
let y = IU.Unit(())
let z = [3.14]

let showI (v) = 
    match box v with
    | :? IU -> 
        match v with
        | Int(_) -> "an IU int"
        |_ -> "not a IU.int"
    |_ -> "not a IU.int"

But I am not happy with the internal match in the showI function. I would prefer something like:

let showI (v) = 
    match box v with
    | :? IU.Int -> "an int"
    |_ -> "not a IU.int"

which does not compile (error: type Int is not defined).

Is there any obvious syntax that I skipped? Thank.

Note: the showI function accepts a variable with an unknown type; this is the reason for the stinky box v.

+4
source share
2 answers

As others have noted, I don't think there is a built-in language feature that allows you to do this. However, you can define an active template that performs a type test:

let (|IsIU|_|) (candidate : obj) =
    match candidate with
    | :? IU as iu -> Some iu
    | _ -> None

This active template has a type obj -> IU option.

, :

let showI = function
    | IsIU (IU.Int i) -> "an IU int"
    | _ -> "not a IU.int"

IsIU , IU.Int.

FSI, x, y z, OP:

> showI x;;
val it : string = "an IU int"
> showI y;;
val it : string = "not a IU.int"
> showI z;;
val it : string = "not a IU.int"
+5

, , IU.Int , case Int IU.

let x = IU.Int(3)

x IU, IU.Int. obj UI.Int :?.

, F # a-la Javascript, . , , , , obj, , , .

F # DU, , , , IU (IU.Int IU.Unit)

let showI (v : IU) =  // explicit argument type is added to illuminate the point
    match v with
    | IU.Int(x) -> sprintf "a IU.Int(%i) value" x
    | _ -> "a IU.Unit"

, showI , IU, , .

: , match, , when guard, , :

open Microsoft.FSharp.Reflection

let showI (v) = 
    match box v with
    | :? IU as x when (fst(FSharpValue.GetUnionFields(x, typeof<IU>))).Name.Equals("Int")
        -> "an IU.Int"  
    | _ -> "not an IU.Int"
+1

Source: https://habr.com/ru/post/1599676/


All Articles