grade_report.dart in Dart
Report cards from a const roster, a switch expression, and padding.
// Average each student's scores and print a letter-grade report card.
class Student {
final String name;
final List<int> scores;
const Student(this.name, this.scores);
double get average =>
scores.fold(0, (sum, s) => sum + s) / scores.length;
}
const roster = [
Student('Ada', [92, 88, 97]),
Student('Grace', [84, 91, 78]),
Student('Alan', [70, 66, 74]),
Student('Edsger', [58, 67, 61]),
];
String letter(double avg) => switch (avg) {
>= 90 => 'A',
>= 80 => 'B',
>= 70 => 'C',
>= 60 => 'D',
_ => 'F',
};
void main() {
final sorted = [...roster]..sort((a, b) => a.name.compareTo(b.name));
print('student avg grade');
for (final s in sorted) {
final name = s.name.padRight(8);
final avg = s.average.toStringAsFixed(1).padLeft(4);
print('$name $avg ${letter(s.average)}');
}
final all = roster.expand((s) => s.scores).toList();
final classAvg = all.fold(0, (sum, s) => sum + s) / all.length;
print('Class average: ${classAvg.toStringAsFixed(1)}');
}
How it works
Studentcomputes itsaveragewith afoldgetter.lettermaps averages to grades with relational patterns.expandpools every score for the class average.
Keywords and builtins used here
StringStudentclassconstdoublefinalforgetinintswitchthisvoid
The run, in numbers
- Lines
- 38
- Characters to type
- 954
- Tokens
- 341
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 315 seconds.
Step 2 of 3 in Encore, step 26 of 27 in Language basics.