在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变量,并可以访问其属性。 可能吗?有更好的构造吗?
答案 0 :(得分:2)
您可以使用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