【发布时间】:2020-11-22 10:37:55
【问题描述】:
我正在尝试读取文件 employees.txt 并输出 payroll.txt 文件。员工文件包含以下文本:H|1111|Jane Doe|8.50|40.0 S|2222|John Doe|0.10|1500.00。我正在尝试读取此文件并输出相同的员工,但已经评估了薪水。问题是我不太了解 File.ReadLines "employees.txt" 背后的逻辑
|> Seq.map inputline_to_employee
|> Seq.map employee_to_outputline 这是代码
open System
open System.IO
type Employee =
| HourlyEmployee of
id: string * name: string * pay_rate: float * hours_worked: float
| SalesEmployee of
id: string * name: string * comm_rate: float * sales_amount: float
// inputline_to_student : string -> Student
// Returns a student record for the given input line.
let inputline_to_employee (line : string) =
let fields = line.Split '|'
[
if (fields.[0] = "H") then HourlyEmployee(fields.[1], (fields.[2] + " " + fields.[3]), float fields.[4], float fields.[5])
else SalesEmployee(fields.[1], (fields.[2] + " " + fields.[3]), float fields.[4], float fields.[5])
]
let payroll = function
| HourlyEmployee (_, _, pay, hrs) -> if (hrs <= 40.) then pay * hrs
else pay * 40. + (hrs * 1.5 * pay)
| SalesEmployee (_, _, comm, amt) -> comm * amt
// employee_to_outputline : Employee -> string
// Returns the output line for the given employee.
let employee_to_outputline emp =
let pay = payroll emp
match emp with
| HourlyEmployee (id, name, _, _) ->
sprintf "%s|%s|%.1f" id name pay
| SalesEmployee (id, name, _, _) ->
sprintf "%s|%s|%.1f" id name pay
// main: string [] -> int
// Entry point of the program.
[<EntryPoint>]
let main _ =
let mutable exit_code = 0
try
let wages =
File.ReadLines "employees.txt"
|> Seq.map inputline_to_employee
|> Seq.map employee_to_outputline
File.WriteAllLines ("payroll.txt", wages)
Console.WriteLine "All employees were read and evaluations were written."
with
:? FileNotFoundException as e ->
Console.Error.WriteLine ("Error: {0}", e.Message)
exit_code <- 1
exit_code
业务逻辑有效,因为我使用员工数组运行它,但由于某种原因,我无法改为读取文件。我知道我传递给函数的 Seq.map 的一些内容。但是我对这种语言比较陌生。
【问题讨论】:
标签: f#