I'm trying to read a File, employees.txt and output a payroll.txt File. The employee file has the following text: H|1111|Jane Doe|8.50|40.0 S|2222|John Doe|0.10|1500.00
. I'm trying to read this file and output the same employees but with salary evaluate already. The thing is that I don't understand very well the logic behind File.ReadLines "employees.txt" |> Seq.map inputline_to_employee |> Seq.map employee_to_outputline Here's the code
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
The issue that I'm having is this
The business logic works because I ran it using an array of Employees, but for some reason I can't get this reading the file instead. I know is something about the Seq.map that I'm passing to the functions. BUt I'm relatively new to this language.
inputline_to_employee is returning a list via []. It should instead return the single employee rather than a list with only one entry.
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.