f# - F# 作业简介
问题描述
附件是一个文本 csv 数据库文件,其中包含名为 Students.txt 的学生信息。该信息包括名字、中间名首字母、姓氏、电话号码、电子邮件和 gpa。您必须编写一个 F# 程序:
- 在适当的地方添加了从斯坦福转学的 Malachi Constant,具有 4.0 gpa 以及任何电话号码和电子邮件地址,
- 打印有多少学生的 gpa 为 3.0 或更高,
- 打印姓氏为 Anderson 的所有学生的姓名(名字、中间名首字母、姓氏)和 gpa,
- 打印有多少学生没有电子邮件帐户,
- 打印所有学生的平均 gpa。
使用电话号码、电子邮件地址和 4.0 gpa 添加 Malachi Constant 后,您应该会发现以下内容:
- 4166 名学生的 gpa 为 3.0 或更高,
- 有 20 个安德森(全部打印出来),
- 有 19 名学生没有电子邮件地址,
- 平均gpa是2.80284235950596,
- 共有10,491名学生。
解决方案
虽然缺少编写完整程序的关键信息,但所要求的大部分内容只需要几行代码。让我们从 CSV 文件中的行建模开始,然后为第 2 点到第 5 点编写一些基本代码:
type Phone = Phone of string
type Email = Email of string
type StudentInfo =
{ firstName : string;
middleInitial : char option;
lastName : string;
phone : Phone;
email : Email option;
gpa : float }
// Three functions below left incomplete due to missing
// information, and/or as an exercise to the reader
let createPhone input = […]
let createEmail input = […]
let readStudentsFromCSV filename = […]
let students = readStudentsFromCSV "Students.txt"
// Print how many students have a 3.0 gpa or higher
students
|> List.filter (fun s -> s.gpa >= 3.0)
|> List.length
|> printfn "%d students have a GPA of 3.0 or higher."
// Print name (first, middle initial, last) and gpa
// of all students with the last name Anderson
students
|> List.filter (fun s -> s.lastName = "Anderson")
|> List.iter (fun s ->
printfn "%s %s%s — GPA: %f"
s.firstName
(match s.middleInitial with
| None -> ""
| Some c -> string c + " ")
s.lastName
s.gpa)
// Print how many students do not have an email account
students
|> List.filter (fun s -> Option.isNone s.email)
|> List.length
|> printfn "%d students do not have an email account."
// Print the average gpa of all students
students
|> List.averageBy (fun s -> s.gpa)
|> printfn "Average GPA of all students: %f."
推荐阅读
- android - React Native 应用程序中的通知声音设置对话框,例如 WhatsApp
- c# - Visual Studio 2019 中的“项目位置”设置存储在哪里?
- python - 无法从 python 计算器获得正确的输出
- automation - ansible 角色的常见用例
- python-3.x - 这个循环不会执行它之后的代码
- c++ - 在 c++ 中,将取消引用的后自增指针分配给另一个已取消引用的后自增指针的结果是什么?
- excel - “1004”:该排序引用无效。确保它在您要排序的数据内,并且第一个排序依据框不是相同的或空白的
- node.js - 保持获取最新数据
- arrays - 在视图控制器上放置无限的 uiview 对象数组
- android - Android以编程方式将域和IP添加到主机文件