Using std.algorithm.map with member functions in D2

I have:

Foo foo = new Foo();

foreach (i; 0..10)
{
  Bar bar = foo.getBar(i);
  ...
}

I want to be able to say instead (equivalently):

foreach (bar; foo.getAllBars())
{
  ...
}

How can i implement getAllBars()?

I figured out something like this:

class Foo
{
  auto getAllBars()
  {
    return map!(getBar)(iota(10));
  }
}

But you cannot do this, of course, because it getBardepends on a parameter thisthat goes beyond the scope. The same applies if you try to create a local functionor delegate. I also thought about creating a function object using opCall, but you cannot use those that have map(can you?).

Some requirements:

  • The returned range should be lazy (so don't copy it to the array first)
  • Suppose that getBaris the only way to get data.
  • , (.. ).
+3
1

std.algorithm.map , - . ( D) , , , - . ( ). , digitalmars.d, .

+1

Source: https://habr.com/ru/post/1767708/


All Articles