www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Generate range

reply John Chapman <johnch_atms hotmail.com> writes:
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)) {
   }
Oct 22 2018
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Oct 22 2018
parent John Chapman <johnch_atms hotmail.com> writes:
On Monday, 22 October 2018 at 23:02:35 UTC, Ali Çehreli wrote:
 iota and map:
Thank you. And the funny thing is I used iota earlier today but it didn't occur to me for this!
Oct 22 2018