numericValue for (unicode) characters

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jan 3 13:49:28 PST 2013


On Thu, Jan 03, 2013 at 08:40:47PM +0100, monarch_dodra wrote:
[...]
> Or, you know... I could just implement both at the same time. It's
> not like there's an *urgency* for the ascii version or anything. I
> think I'll just do that.
> 
> So... do we agree on
> ascii: int - not found => -1
> uni: double - not found => nan
[...]

LGTM. :)

I did think of what might happen if somebody wrote an int cast for
std.uni.numericValue:

	void sloppyProgrammersFunction(dchar ch) {
		// First attempt: compiler error: can't implicitly
		// convert double -> int ...
		//int val = std.uni.numericValue(ch);

		// ... so sloppy programmer inserts a cast
		int val = cast(int)std.uni.numericValue(ch);

		// On Linux/64, if numericValue returns nan, this prints
		// -int.max.
		writeln(val);

		// So this should work:
		if (val < 0) {
			// (In fact, it will still work if
			// std.ascii.numericValue were used instead.)
			writeln("Sloppy code caught the problem correctly!");
		}
	}

So it seems that everything should be alright.

This particular example occurred to me, 'cos I'm thinking of how often
one wishes to extract an integral value from a string, and usually one
doesn't think that floating point is necessary(!), so the cast from
double is a rather big temptation (even though it's wrong!).


T

-- 
Tell me and I forget. Teach me and I remember. Involve me and I understand. -- Benjamin Franklin


More information about the Digitalmars-d mailing list