to!()() & leading/trailing whitespace

bearophile bearophileHUGS at lycos.com
Mon Aug 16 15:35:51 PDT 2010


This post is about this enhancement request of mine that recently David Simcha has closed as wontfix:
http://d.puremagic.com/issues/show_bug.cgi?id=4165

This topic is about a small Phobos thing, it's not about large complex things as the const system. But it's relevant because I have hundreds of Python scripts (and many small D1 programs) that essentially load some numbers from textual files, process them, and write the numbers in other textual files. My textual files are often small, but I have many of them, and I like to see them processed quickly and safely, and I like to write those little programs in a short time. So reading numbers from a text file is an essential operation for me. And when I read textual files it's common to have leading newlines (whitespace) behind numbers.

David has closed 4165 because:
- It's by design (it's mentioned in the docs of std.conv). But I don't care of this, I think this it's a wrong design.
- There's a trivial workaround: this is true, but you need to remember to use this workaround, it may cause bugs (bugs == the program doesn't work), and I don't see the point in using a workaround very often in my code, I prefer to!() to do that by itself.

In practice sometimes I use printf() in those D scripts to print many numbers because it's much faster than writeln(). So I can write and use a more efficient function that converts strings to numbers, but I'd like to need Phobos only for such basic and common operation.



Possible disadvantages of a to!int() (and similar to!double(), etc) that ignores leading and trailing whitespace:

It introduces bugs, because it accepts a more sloppy input: from my experience this is not true, in Python int() and float() ignore the leading/trailing whitespace and in years I don't remember it ever causing bugs to me:
>>> int(" -125\n")
-125
>>> float(" 6.3e6\t")
6300000.0

Phobos functions are meant as the most simpler bricks, that you may compose to perform more complex operations: this is generally true and good, but Python shows that when two or few operations are frequently done attached to each other, it's good to put inside the std lib something the performs the composed thing in one go, because it helps chunk the code and makes the code shorter and more readable, and decreases the chance for bugs. When I read numbers from files I will need to use to!int(txt.strip()) often.

Bye,
bearophile


More information about the Digitalmars-d mailing list