首页 > 解决方案 > F# 作业简介

问题描述

附件是一个文本 csv 数据库文件,其中包含名为 Students.txt 的学生信息。该信息包括名字、中间名首字母、姓氏、电话号码、电子邮件和 gpa。您必须编写一个 F# 程序:

  1. 在适当的地方添加了从斯坦福转学的 Malachi Constant,具有 4.0 gpa 以及任何电话号码和电子邮件地址,
  2. 打印有多少学生的 gpa 为 3.0 或更高,
  3. 打印姓氏为 Anderson 的所有学生的姓名(名字、中间名首字母、姓氏)和 gpa,
  4. 打印有多少学生没有电子邮件帐户,
  5. 打印所有学生的平均 gpa。

使用电话号码、电子邮件地址和 4.0 gpa 添加 Malachi Constant 后,您应该会发现以下内容:

  1. 4166 名学生的 gpa 为 3.0 或更高,
  2. 有 20 个安德森(全部打印出来),
  3. 有 19 名学生没有电子邮件地址,
  4. 平均gpa是2.80284235950596,
  5. 共有10,491名学生。

标签: f#

解决方案


虽然缺少编写完整程序的关键信息,但所要求的大部分内容只需要几行代码。让我们从 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."

推荐阅读