typestar

grade_report.ml in OCaml

Report cards from a record roster, an if ladder, and printf columns.

(* Average each student's scores and print a letter-grade report. *)

type student = { name : string; scores : int list }

let roster = [
  { name = "Ada"; scores = [92; 88; 97] };
  { name = "Grace"; scores = [84; 91; 78] };
  { name = "Alan"; scores = [70; 66; 74] };
  { name = "Edsger"; scores = [58; 67; 61] };
]

let average s =
  let total = List.fold_left ( + ) 0 s.scores in
  float_of_int total /. float_of_int (List.length s.scores)

let letter avg =
  if avg >= 90.0 then 'A'
  else if avg >= 80.0 then 'B'
  else if avg >= 70.0 then 'C'
  else if avg >= 60.0 then 'D'
  else 'F'

let () =
  print_endline "student  avg grade";
  roster
  |> List.sort (fun a b -> compare a.name b.name)
  |> List.iter (fun s ->
      let avg = average s in
      Printf.printf "%-8s %4.1f  %c\n" s.name avg (letter avg));

  let all = List.concat_map (fun s -> s.scores) roster in
  let class_avg =
    float_of_int (List.fold_left ( + ) 0 all)
    /. float_of_int (List.length all)
  in
  Printf.printf "Class average: %.1f\n" class_avg

How it works

  1. student is a record; the roster is a list literal.
  2. letter grades through an if/else ladder to a char.
  3. List.concat_map pools every score for the class average.

Keywords and builtins used here

The run, in numbers

Lines
36
Characters to type
975
Tokens
274
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 274 seconds.

Type this snippet

Step 2 of 3 in Encore, step 28 of 29 in Language basics.

← Previous Next →