grade_report.jl in Julia
Report cards from a struct roster, guard-clause grading, and vcat.
# Average each student's scores and print a letter-grade report card.
using Printf
struct Student
name::String
scores::Vector{Int}
end
roster = [
Student("Ada", [92, 88, 97]),
Student("Grace", [84, 91, 78]),
Student("Alan", [70, 66, 74]),
Student("Edsger", [58, 67, 61]),
]
average(s::Student) = sum(s.scores) / length(s.scores)
function letter(avg)
avg >= 90 && return 'A'
avg >= 80 && return 'B'
avg >= 70 && return 'C'
avg >= 60 && return 'D'
return 'F'
end
println("student avg grade")
for s in sort(roster, by = s -> s.name)
@printf("%-8s %4.1f %c\n", s.name, average(s), letter(average(s)))
end
all_scores = reduce(vcat, [s.scores for s in roster])
@printf("Class average: %.1f\n", sum(all_scores) / length(all_scores))
How it works
Studentholds a name and scores;averageis one line.letterreturns through a ladder of&&guards.reduce(vcat, ...)pools every score for the class average.
Keywords and builtins used here
IntStringStudentVectorendforfunctioninreturnstructusing
The run, in numbers
- Lines
- 33
- Characters to type
- 734
- Tokens
- 213
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 197 seconds.
Step 2 of 3 in Encore, step 26 of 27 in Language basics.