Intro to F# assignment

Attached is a text csv database file containing student information named Students.txt. The info includes a first name, middle initial, last name, phone number, email and gpa. You must write an F# program that:

  1. adds Malachi Constant, a transfer from Stanford, in the appropriate spot with a 4.0 gpa and any phone number and email address,
  2. prints how many students have a 3.0 gpa or higher,
  3. prints the name (first, middle initial, last) and gpa of all students with the last name Anderson,
  4. prints how many students do not have an email account,
  5. prints the average gpa of all students.

After you add Malachi Constant with a phone number, email address and 4.0 gpa, you should find the following:

  1. 4166 students have a 3.0 gpa or higher,
  2. there are 20 andersons (print them all out),
  3. there are 19 students with no email address,
  4. the average gpa is 2.80284235950596,
  5. there are 10,491 students total.

1 answer

  • answered 2018-11-08 10:11 dumetrulo

    While there is crucial information missing to write a complete program, most of what is asked requires only a few lines of code. Let's start with modelling the rows in the CSV file, then write some rudimentary code for points 2 to 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."