eliminate cast

downs default_357-line at yahoo.de
Wed May 14 09:35:44 PDT 2008


Dee Girl wrote:
> There is a file data.txt with numbers:
> 
> 345
> 5467
> 45
> 238
> ...
> 
> And I want to load into an array of uint like this.
> 
> auto sizes = map!
>     (to!(uint, string))
>     (compose!(split, q{cast(string) std.file.read(a)})("data.txt"));
> 
> It works but cast is always bad ^_^.

Where did you get that idea?
In this case, basically, we know the file is really text. So we put this knowledge into code by assuring the compiler that yes, the arbitrary data you've just read _is_ text after all.
In any case, it's just a reinterpreting cast. It doesn't change any actual data. So no time lost.

Also, just fyi, here's how that code would look like in tools.functional:

gentoo-pc ~ $ cat test2.d; echo -----; rebuild test2.d -oftest2 && ./test2
module test2;
import std.stdio, std.file, tools.functional, std.string: split, atoi;
void main() {
  auto sizes = (cast(string) "test.txt".read()).split() /map/ &atoi;
  writefln(sizes);
}
-----
[345,5467,45,238]


I still prefer infix ^^

 --downs



More information about the Digitalmars-d mailing list