Search code examples
listf#recorddiscriminated-union

access data from a record in a discriminated union


Having this setup, how do I loop through list and print data about each employee?

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 }]

Solution

  • Typically, I'd recommend breaking this into pieces.

    Start with a function for each portion, such as a function to print each person (or convert to string, which is often easier to reuse and compose), then a second function that uses that to convert an employee to a string.

    Finally, you can use List.iter to iterate your list to print:

    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")