Phobos2: zip, integral ranges, map, Any, All, Map

dsimcha dsimcha at yahoo.com
Tue Apr 28 06:57:28 PDT 2009


== Quote from bearophile (bearophileHUGS at lycos.com)'s article
> Some more notes about Phobos2. Some of the things I say may be wrong because my
experience with Phobos2 is limited still.
> Daniel Keep:
> > Not true.  Here's an excellent reason to use ranges over opApply: you
> > can't define zip with opApply.  Because opApply uses inversion of
> > control, you can't use more than one without bringing threads into the
> > equation.
> I'll try to zip two ranges that return the leaves of two different binary trees.
This can be a simple example to show to attract people to D2 language :-)
> So I've tried using zip:
> import std.range: zip;
> import std.stdio: writeln;
> void main() {
>     auto a = [1, 2, 3];
>     string[] b = ["a", "b", "c"];
>     foreach (xy; zip(a, b))
>         writeln(xy.at!(0), " ", xy.at!(1));
> }
> That doesn't work:
> ...\dmd\src\phobos\std\range.d(1847): Error: template instance
Zip!(int[3u],immutable(char)[][]) does not match template declaration Zip(R...) if
(R.length && allSatisfy!(isInputRange,R))
> probably because 'a' is a static array. Is isInputRange false for static arrays?

Yes, because the range interface for arrays relies on std.array being imported and
using extension method syntax.  This has bitten me a bunch of times, too.  The
functions in std.array take dynamic arrays and static arrays are not implicitly
convertible to dynamic arrays, except in the specific case of binding an array
literal to a variable.  Whether they should be, I don't know.
> ------------
> The most basic and useful range is the one of integer numbers. How can I create
with Phobos2 lazy and eager ranges like the following ones?
> >>> range(1, 5)
> [1, 2, 3, 4]
> >>> range(5, 1, -1)
> [5, 4, 3, 2]
> >>> list(xrange(5, 10))
> [5, 6, 7, 8, 9]
> >>> list(xrange(5, 10, 2))
> [5, 7, 9]
> Similar ranges are useful with map,zip, and in many other situations.
> (I hope the x..y range syntax of D2 foreach will evolve in a syntax that can be
used everywhere an integral range can be used).

I think you're looking for std.range.iota, although it doesn't work so well right
now because of bug 2871.





More information about the Digitalmars-d mailing list