eliminate cast

bearophile bearophileHUGS at lycos.com
Wed May 14 14:38:39 PDT 2008


My libs are designed to solve exactly such problems, this is the lib:
http://www.fantascienza.net/leonardo/so/libs_d.zip

Usage examples to do the things shown in this thread:

import std.string: stripr;
import std.conv: toInt;
import d.func: map, xrange, range, toStruct, cinterval, zip;
import d.string: xsplit, putr;
import d.xio: xfile;

void main() {
  auto values = map((string l){return toInt(stripr(l));}, xfile("test.txt"));
  putr(values);

  // mapping on two joined iterable things:
  auto arr = map((int x){return -x;}, xrange(6) ~ [1, 2, 3]);
  putr(arr);

  // zipping int a struct array:
  auto array1 = range(3, 30, 2);
  auto array2 = cinterval('b', 'h');
  auto pairs = map((int i, char c){return toStruct(i, c);}, array1, array2);

  // Or just:
  putr(pairs);
  putr(zip(array1, array2));
}


The output is verbatim:
[345, 5467, 45, 238]
[0, -1, -2, -3, -4, -5, -1, -2, -3]
[<3, 'b'>, <5, 'c'>, <7, 'd'>, <9, 'e'>, <11, 'f'>, <13, 'g'>, <15, 'h'>]
[<3, 'b'>, <5, 'c'>, <7, 'd'>, <9, 'e'>, <11, 'f'>, <13, 'g'>, <15, 'h'>]

Note that xfile() is lazy and it returns strings, so if the file is large it doesn't build a huge array of lines.

If you want there is an xmap() too that is lazy, and allows you the lazy printing too.

The putr() is able to print any struct too, putting it inside <...>.

cinterval gives a (closed on the right too) interval of chars.

std.conv.toInt() is stupid, it's not even able to strip spaces by itself... so I've used the (quite slow) std.string.stripr().

The ~ after the xrange to chain those sequences is possible because all lazy iterators (like xrange) support the xchain protocol, but you can use the xchain() thing by itself too, for example if you want to chain two arrays, or you can add the Chainable mixin to your iterable classes.

There are full ddocs with examples and full coverage unittests for everything that's present in the lib.

Bye,
bearophile



More information about the Digitalmars-d mailing list