Generate range

Ali Çehreli acehreli at yahoo.com
Mon Oct 22 23:02:35 UTC 2018


On 10/22/2018 03:51 PM, John Chapman wrote:
> Given a function that returns a count of items, and another function 
> that returns an item at an index, is there anything built into Phobos 
> that can use them together to build a range?
> 
> The two functions are from an external API, eg:
> 
>    int getFontCount();
>    Item getItemAt(int index);
> 
> I was wondering if there was something like a "rangeOf" as illustrated:
> 
>    foreach (item; rangeOf!(() => getFontCount(), (i) => getItemAt(i)) {
>    }

iota and map:

alias Item = string;

Item[] items = [ "Good font", "Better font" ];

int getFontCount() {
     import std.conv : to;
     return items.length.to!int;
}

Item getItemAt(int index) {
     return items[index];
}

auto allFonts() {
}

auto itemRange() {
     import std.range : iota;
     import std.algorithm : map;
     return iota(getFontCount()).map!(i => getItemAt(i));
}

void main() {
     import std.stdio;
     writeln(itemRange());
}

Ali


More information about the Digitalmars-d-learn mailing list