F#-模式匹配判别联合并访问对象的属性

时间:2019-01-11 15:18:27

标签: f# pattern-matching

在F#旅游中,我有这个例子

type Person = {
    First : string
    Last  : string
 }

/// A Discriminated Union of 3 different kinds of employees
type Employee =
    | Engineer of engineer: Person
    | Manager of manager: Person * reports: List<Employee>
    | Executive of executive: Person * reports: List<Employee> * assistant: Employee

let rec findDaveWithOpenPosition(emps: List<Employee>) = 
    emps
    |> List.filter(function 
                    | Manager({First =  "Dave"}, []) -> true
                    | Executive({First = "Dave"}, [], _) -> true
                    | _ -> false
                    )

但是我想在匹配对象之后访问对象,像这样:

let rec findDaveWithOpenPos2(emps: List<Employee>) =
    List.filter (fun (e:Employee) ->
                    match e with
                        | Manager({First = "Dave"}, []) -> e.Last.Contains("X") //Does not compile
                        | Executive({First = "Dave"}, [], _) -> true
                        | _ -> false
                    ) emps

因此,我想在右侧静态输入“ e”作为Person或Employee或Manager变量,并可以访问其属性。 可能吗?有更好的构造吗?

1 个答案:

答案 0 :(得分:2)

您可以使用PersonManager情况下命名as实例:

let rec findDaveWithOpenPos2(emps: Employee list) =
    List.filter (fun (e:Employee) ->
                    match e with
                        | Manager({First = "Dave"} as p, []) -> p.Last.Contains("X")
                        | Executive({First = "Dave"}, [], _) -> true
                        | _ -> false
                    ) emps