toString method
A string representation of this object.
Some classes have a default textual representation,
often paired with a static parse
function (like int.parse).
These classes will provide the textual representation as
their string representation.
Other classes have no meaningful textual representation
that a program will care about.
Such classes will typically override toString
to provide
useful information when inspecting the object,
mainly for debugging or logging.
Implementation
@override
String toString() {
final coeffs = getCoefficients();
String mono(Rat n, int k, bool first) {
if (k == 0) {
return '$n';
}
if (n == Rat.one) {
if (k == 1) {
return 'x';
} else {
return 'x ^ $k';
}
} else {
final n2 = first ? n : n.abs();
if (k == 1) {
return '$n2 * x';
} else {
return '$n2 * x ^ $k';
}
}
}
final nonzero = List.generate(coeffs.length, (i) => i)
.where((i) => !coeffs[i].isZero)
.toList();
if (nonzero.length == 1) {
return 'irrational(${mono(
coeffs[nonzero[0]],
nonzero[0],
true,
)})';
}
final result = StringBuffer('irrational(');
for (var i = 0; i < nonzero.length; i++) {
final ni = nonzero[i];
final coeff = coeffs[ni];
if (i != 0) {
if (coeff.isNegative) {
result.write(' - ');
} else {
result.write(' + ');
}
}
result.write(mono(coeff, ni, i == 0));
}
result.write(')');
return '$result';
}