首页 > 解决方案 > 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
   


标签: f#recorddiscriminated-union

解决方案


您需要像这样在受歧视的工会上进行匹配:

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 

推荐阅读