www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Filter a Range Based on a Passed In Variable

reply jsako <spam spam.com> writes:
I want to be able to filter a range based on a variable known at 
runtime. Something like this:

[code]
int id = getFilterID();

auto filteredRange = filter!(a => a.id == id)(rangeToBeFiltered);

[/code]

This doesn't seem to be possible, however as .filter only takes 
unary predicates. I tried:

[code]

filterString = "a.id == " ~ to!string(id);
filter!filterString(rangeToBeFiltered);

[/code]

But that also doesn't work. Is there another range algorithm that 
should be used in this case? Do I roll my own?
Jan 20
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Saturday, 20 January 2018 at 19:04:06 UTC, jsako wrote:
 I want to be able to filter a range based on a variable known 
 at runtime. Something like this:

 [code]
 int id = getFilterID();

 auto filteredRange = filter!(a => a.id == 
 id)(rangeToBeFiltered);

 [/code]

 This doesn't seem to be possible, however as .filter only takes 
 unary predicates. I tried:
That should actually work. What exactly happened when you ran that literal code above?
Jan 20
parent jsako <spam spam.com> writes:
On Saturday, 20 January 2018 at 19:09:28 UTC, Adam D. Ruppe wrote:
 On Saturday, 20 January 2018 at 19:04:06 UTC, jsako wrote:
 I want to be able to filter a range based on a variable known 
 at runtime. Something like this:

 [code]
 int id = getFilterID();

 auto filteredRange = filter!(a => a.id == 
 id)(rangeToBeFiltered);

 [/code]

 This doesn't seem to be possible, however as .filter only 
 takes unary predicates. I tried:
That should actually work. What exactly happened when you ran that literal code above?
... Huh. The code I posted was a simplified case of what I actually have and like a fool I didn't test it first. You're absolutely right, the above code does work. Color me embarrassed. In the actual code, I kept getting DMD saying "...does not match template declaration filter(alias predicate) if (is(typeof(unaryFun!predicate)))". I think it may be a scoping issue? I'll have to look closer at it. Thanks for the help! Sorry I wasted your time. At least this pointed me in the right direction to find out what is really going on.
Jan 20