如何通过值来进行递归区分联合?

sgt*_*gtz 0 f#

在F#中,是否可以根据类型和值来区分联合?

这是在不知道语法应该是什么样的情况下尝试表达这一点.

type Foo =
    | A of int * Foo
    | B of string where B.name = "1" * Foo
    | C of string where C.name = "2" * Foo
    | Empty
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 5

我不完全确定你想要实现的目标.但是,如果你想创建一个具有name属性的类型,当类型为"1"时,属性为B"2" C,那么你可以添加一个成员:

type Foo =
  | A of int * Foo
  | B of Foo
  | C of Foo
  | Empty
  member x.Name = 
    match x with
    | B _ -> "1"
    | C _ -> "2"
    | _ -> failwith "Name is not available!"
Run Code Online (Sandbox Code Playgroud)

如果您希望在模式匹配中使用数字,则可以定义活动模式.假设你有一个只有AB(有一个名字)的类型:

type Foo = 
  | A of int
  | B of string * Foo
Run Code Online (Sandbox Code Playgroud)

现在,你可以写上的有源图案,让你区分A,B名称为"1",B名称为"2":

let (|A|B1|B2|) x = 
  match x with
  | A n -> A n
  | B("1", foo) -> B1 foo
  | B("2", foo) -> B1 foo
  | _ -> failwith "Invalid B"
Run Code Online (Sandbox Code Playgroud)

如果您现在有一个值foo,则可以针对这三种情况进行模式匹配:

match foo with
| A n -> ...
| B1 subfoo -> ...
| B2 subfoo -> ...
Run Code Online (Sandbox Code Playgroud)