grade_report.fsx in F#
Report cards from a record roster, a guarded match, and printf columns.
// Average each student's scores and print a letter-grade report card.
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 student =
student.Scores |> List.sumBy float
|> fun total -> total / float (List.length student.Scores)
let letter avg =
match avg with
| a when a >= 90.0 -> "A"
| a when a >= 80.0 -> "B"
| a when a >= 70.0 -> "C"
| a when a >= 60.0 -> "D"
| _ -> "F"
printfn "student avg grade"
for s in roster |> List.sortBy (fun s -> s.Name) do
let avg = average s
printfn "%-8s %4.1f %s" s.Name avg (letter avg)
let classAvg =
roster |> List.collect (fun s -> s.Scores)
|> List.averageBy float
printfn "Class average: %.1f" classAvg
How it works
Studentis a record; the roster is a list literal.lettergrades through a ladder ofwhenguards.List.collectpools every score for the class average.
Keywords and builtins used here
Studentdofloatforfuninletlistmatchstringtypewhenwith
The run, in numbers
- Lines
- 31
- Characters to type
- 843
- Tokens
- 248
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 248 seconds.
Step 2 of 3 in Encore, step 26 of 27 in Language basics.