About to!int

Jonathan M Davis jmdavisProg at gmx.com
Tue Jan 31 02:09:51 PST 2012

On Monday, January 30, 2012 21:01:38 bearophile wrote:
> In Python int() and float() convert a string into a number even if it 
contains some whitespace before and after the number:
> >>> s = " 12\n"
> >>> int(s)
> 12
> >>> float(s)
> 12.0
> In D  to!int(" 12\n")  gives a run-time error. So time ago I have weakly
> asked Andrei to change to!int, to let it ignore leading and trailing
> whitespace, but he has ignored my request.
> A leading newline comes often from input stdin.readln() and other sources.
> So in D you need to add a strip():
> int n = to!int(stdin.readln().strip());
> I sometimes forget to add the strip(). Do you know why Andrei has not
> appreciated the idea of to!int and similar functions to ignore leading and
> trailing whitespace?

He's probably completely forgotten about it, and it's the sort of thing that 
he's likely to consider bikeshedding at this point - particularly since he's 
increasingly against making small changes like this.

Also, the argument can easily be made that " 10 " is _not_ a number. It's a 
number surrounded by spaces. In general, std.conv.to does exact conversions, 
and to!int(" 10 ") is _not_ an exact conversion, since it includes characters 
which are not digits or a leading minus sign. std.conv.parse, on the other 
hand, deals with the spaces, because it's parsing the string rather than 
converting the whole thing.

Also, if you _want_ to do an exact conversion, and std.conv.to removed the 
whitespace for you, then you couldn't use std.conv.to. You'd have to create 
your own. On the other hand, if you want to ignore whitespace in the 
conversion, you can easily wrap std.conv.to to do it. So, it's more composable 
as it is.

There are obviously arguments for having std.conv.to ignore whitespace as well 
(you're making them), but at this point, I think that it's simply a matter of 
using parse rather than std.conv.to (or stripping the string first) if you want 
to ignore whitespace. I don't see std.conv.to changing. And as far Andrei, as 
I said, he's increasingly against making small changes like this. He wants 
substantial work done, not arguments over shifting around small stuff.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list