代码之家  ›  专栏  ›  技术社区  ›  Bartek Wójcik

f-模式匹配区分联合和访问对象属性

  •  1
  • Bartek Wójcik  · 技术社区  · 6 年前

    从F Tour我有这个例子

    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”作为人员、员工或经理变量,以访问其属性。 有可能吗?有更好的建筑吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Lee    6 年前

    你可以说出 Person 中的实例 Manager 用例 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