【问题标题】:F# - Pattern matching discriminated union and accessing object's propertiesF# - 模式匹配区分联合和访问对象的属性
【发布时间】:2019-06-06 12:57:38
【问题描述】:

来自 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”作为 Person 或 Employee 或 Manager 变量,并可以访问它的属性。 可能吗?有没有更好的结构?

【问题讨论】:

    标签: f# pattern-matching


    【解决方案1】:

    您可以使用asManager 案例中命名Person 实例:

    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
    

    【讨论】:

    • 我如何引用对象e:Employee,而不仅仅是p:PersonManager({First = "Dave"}, []) as m-&gt; m... 够吗? p 毕竟是“经理”类型,但我没有这个对象的方法。是因为什么都没有执行吗?但至少应该有一个reports: Employee list 属性。或者它只是元组并且这个reports: Employee list 不是对象p 的一部分?
    • @BartekWójcik - e 已经引用了 Employee,但它没有 Last 成员。 p 的类型为 Person。没有 Manager 类型 - ManagerEmployee 类型的构造函数。
    • @Lee 实际上,F# 的列表被称为List,它的类型别名为list,所以它是正确的类型,除非你打开了System.Collections.Generic
    • @TheQuickBrownFox - 谢谢,从答案中删除。
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 2012-08-27
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多