f# - F# 匹配记录和区分联合
问题描述
我想使用 calculateWage 函数,它给出了一个错误,应该是 Employee 类型,但这里有 Person 类型。
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 calculateWage (employee:Employee) (hours:int) =
match employee with
| {salary_hour= sh} -> (sh * hours)*TAX/100
解决方案
您需要像这样在受歧视的工会上进行匹配:
let calculateWage (employee:Employee) (hours:int) =
match employee with
| Administrator {salary_hour= sh}
| OfficeWorker {salary_hour= sh}
| WarehouseWorker {salary_hour= sh} -> (sh * hours)*TAX/100
在这种情况下,它可能看起来很愚蠢,但请记住,每个有区别的联合案例都可以有不同的数据。
通常,当我最终得到这样的数据时,我会分两步执行此操作。我有一个提取公共数据的函数。还有一个与数据本身一起工作的函数:
let extractPerson employee =
match employee with
| Administrator p
| OfficeWorker p
| WarehouseWorker p -> p
let calculateWage person (hours:int) =
(person.salary_hour * hours)*TAX/100
因此,您最终会得到一些可以轻松编写的函数:
let calculate employee =
employee
|> extractPerson
|> calculateWage
推荐阅读
- r - 从单个变量绘制水平灰度图的概率
- firebase - Firebase minInstances 被忽略
- c# - 试图在我的控制器上添加选择按钮以打开暂停菜单
- amazon-web-services - 如何等待 AWS ElasticBeanstalk 在 CI/CD 期间完成环境更新?
- python - Sublime 在输入时不显示模块内方法的建议
- python - 如何修复 TypeError: unhashable type: 'list'?
- c# - 为什么在 ASP.NET 中有些属性为 null 而有些则不使用 get 方法?
- bash - sed -n 命令或变量替换
- python - 接收 SIGINT 或 SIGTERM 时,Moviepy 上的管道损坏错误
- java - 如何防止基于正在使用的活动弹簧配置文件执行 CommandLineRunner run() 方法?