Bug 14569 – BigInt is not compatible with the type of immutable (char) and has a problem when converting from a type immutable(char)
Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2015-05-11T03:28:37Z
Last change time
2017-09-15T18:39:30Z
Assigned to
No Owner
Creator
dennis.m.ritchie
Comments
Comment #0 by dennis.m.ritchie — 2015-05-11T03:28:37Z
In my opinion, this should be corrected:
import std.stdio : writeln;
import std.conv : to, text;
import std.bigint : BigInt;
void main() {
BigInt twoInThousand = 2.to!BigInt ^^ 1000;
string s = twoInThousand.text;
BigInt sum1, sum2, sum3, sum4;
foreach (e; s) {
// sum1 += e.to!BigInt; // Error: template instance
// std.conv.to!(BigInt).to!(immutable(char)) error instantiating
sum2 += e.to!int; // wrong
sum3 += e.to!uint; // wrong
sum4 += e.text.to!BigInt; // OK
}
writeln(sum2); // 15862 // wrong
writeln(sum3); // 15862 // wrong
writeln(sum4); // 1366 // OK
}
Comment #1 by simen.kjaras — 2017-09-15T18:39:30Z
Your expectations of what e.to!BigInt should do does not square up with what's being done for int and uint, and you even point that out in the bug report itself - e.to!int gives a different result from what you expect. It could be argued that BigInt should have the same behavior as does int and uint, but having a different behavior for BigInt would break the principle of least astonishment, and thus be a Bad Thing™.
Judging from the report, you're implementing a sum of digits. If s in your case was "123", you probably expect sum1, sum2, sum3 and sum4 to be 6, as that would be the sum of digits. As sum2 and sum3 shows, you instead get a sum of the values of the unicode code points making up the string.