从可区分联合中的记录访问数据
access data from a record in a discriminated union
有了这个设置,我如何遍历列表并打印每个员工的数据?
type Person =
{ first_name: string
last_name: string
age: int
salary_hour: int }
type Employee =
| Administrator of Person
| OfficeWorker of Person
| WarehouseWorker of Person
let emps =
[ Administrator
{ first_name = "name"
last_name = "name"
age = 19
salary_hour = 200 }]
通常,我建议将其分解。
从每个部分的函数开始,例如打印每个人的函数(或转换为字符串,这通常更容易重用和组合),然后是第二个函数,使用该函数将员工转换为字符串.
最后,您可以使用 List.iter
迭代您的列表以打印:
let personToString p =
sprintf "%s %s [%d] - Salary %d" p.first_name p.last_name p.age p.salary_hour
let employeeToString e =
match e with
| Administrator a -> sprintf "Administrator: %s" (personToString a)
| OfficeWorker o -> sprintf "Office: %s" (personToString o)
| WarehouseWorker w -> sprintf "Warehouse: %s" (personToString w)
emps |> List.iter (fun e -> employeeToString e |> printfn "%s")
有了这个设置,我如何遍历列表并打印每个员工的数据?
type Person =
{ first_name: string
last_name: string
age: int
salary_hour: int }
type Employee =
| Administrator of Person
| OfficeWorker of Person
| WarehouseWorker of Person
let emps =
[ Administrator
{ first_name = "name"
last_name = "name"
age = 19
salary_hour = 200 }]
通常,我建议将其分解。
从每个部分的函数开始,例如打印每个人的函数(或转换为字符串,这通常更容易重用和组合),然后是第二个函数,使用该函数将员工转换为字符串.
最后,您可以使用 List.iter
迭代您的列表以打印:
let personToString p =
sprintf "%s %s [%d] - Salary %d" p.first_name p.last_name p.age p.salary_hour
let employeeToString e =
match e with
| Administrator a -> sprintf "Administrator: %s" (personToString a)
| OfficeWorker o -> sprintf "Office: %s" (personToString o)
| WarehouseWorker w -> sprintf "Warehouse: %s" (personToString w)
emps |> List.iter (fun e -> employeeToString e |> printfn "%s")