Is this code "D-ish" enough?
lafoldes
lafoldes at geemail.kom
Wed Aug 7 11:25:33 PDT 2013
Hi, this is one of my attempts to code in D:
Given a binary file, which contains pairs of a 4 byte integer and
a zero-terminated string. The number of pairs is known. The task
is to read the pairs, sort them by the integer ("id") part, and
write out the result with line numbers to the console.
I tried to do this using the component paradigm, without extra
classes, helper functions, etc. I've ended up with this code:
{
uint count = 1000;
auto f = File("binary.dat", "rb");
uint id[1];
int lineNo = 0;
repeat(0, count).
map!(t => tuple(f.rawRead(id)[0], f.readln('\0'))).
array.
sort!("a[0] < b[0]").
map!(t => format("%6d %08x %s\n", lineNo++, t[0], t[1])).
copy(stdout.lockingTextWriter);
stdout.flush();
}
Is this code "D-ish" enough?
There are things, I don'like here:
- the dummy repeat at the beginning of the component chain. The
only purpose of it is to produce the needed number of items.
Moreover repeat doesn't produce sortable range, so the array is
needed as well.
- I don't know how to do this when the number of items is nor
known. How to repeat until EOF?
- The variables id, and lineNo outside the chain.
- rawRead() needs an array, even if there is only one item to
read.
- How to avoid the flush() at the end?
What do you think?
More information about the Digitalmars-d-learn
mailing list