sortUniq

Peter Alexander via Digitalmars-d digitalmars-d at puremagic.com
Sat Jan 24 13:53:58 PST 2015


On Saturday, 24 January 2015 at 14:53:02 UTC, Andrei Alexandrescu
wrote:
> On 1/24/15 3:50 AM, Peter Alexander wrote:
>> On Friday, 23 January 2015 at 18:22:08 UTC, zeljkog wrote:
>>> On 23.01.15 19:13, Andrei Alexandrescu wrote:
>>>> On 1/23/15 10:05 AM, zeljkog wrote:
>>>>> On 23.01.15 18:48, H. S. Teoh via Digitalmars-d wrote:
>>>>>>
>>>>>> I think what he's trying to do is to call a function that 
>>>>>> returns a
>>>>>> delegate, and use that delegate to instantiate the filter 
>>>>>> template.
>>>>>> AFAIK I've never seen code like this before, and it looks 
>>>>>> like the
>>>>>> compiler isn't prepared to handle this.
>>>>>>
>>>>>
>>>>> Yes, I tried to use filter for unique, need closure.
>>>>> I think there are many applications for this pattern.
>>>>
>>>> Please post a complete snippet then. Thanks! -- Andrei
>>>>
>>>
>>> import std.stdio, std.algorithm;
>>>
>>> auto unique(){
>>>    bool[int] c;
>>>    return (int a){
>>>        if (a in c)
>>>            return false;
>>>        else{
>>>            c[a] = true;
>>>            return true;
>>>        }
>>>    };
>>> }
>>>
>>> void main()
>>> {
>>>    [1, 5, 5, 2, 1, 5, 6, 6].filter!(unique()).writeln;
>>> }
>>
>> auto f = unique();
>> [1, 5, 5, 2, 1, 5, 6, 6].filter!(f).writeln;  // [1, 5, 2, 6]
>>
>> Filter needs an alias, and you cannot alias an R-value (it has 
>> no symbol).
>
> Hmmm... we do allow rvalues sometimes (e.g. for strings). I 
> think we could and should relax the rule to allow rvalues in 
> this case, too. -- Andrei

I was wrong. R-values work, as long as they are compile time
constants. The problem here is that closures don't yet work in
CTFE (as the error says). Pulling it out as a local variable
works because the alias then binds to the symbol rather than the
value.


More information about the Digitalmars-d mailing list