[ create a new paste ] login | about

Link: http://codepad.org/kmenIDk7    [ raw code | fork ]

D, pasted on May 1:
module inputRangeInterfaceRef;

import std.stdio;
import std.array;

interface InputRange(E) {
    ///
    @property auto ref E front();

    ///
    auto ref E moveFront();

    ///
    void popFront();

    ///
    @property bool empty();

    int opApply(int delegate(ref E));

    /// Ditto
    int opApply(int delegate(ref size_t, ref E));

}

class Foo(E) : InputRange!E
{
    E[] arr;
    
    @property ref E front()
    {
        return arr.front;
    }
    
    auto ref E moveFront() { return arr.front; }
    void popFront() { arr.popFront; }
    @property bool empty() { return !arr.length; }
        
    int opApply(int delegate(ref E) dg) 
    {
        int res;

        for(auto r = arr; !r.empty; r.popFront()) 
        {
            res = dg(r.front);
            if(res) break;
        }

        return res;
    }
    
    
    int opApply(int delegate(ref size_t index, ref E) dg) 
    {
        int res;

        size_t i = 0;
        for(auto r = arr; !r.empty; r.popFront()) 
        {
            res = dg(i, r.front);
            if(res) break;
            i++;
        }

        return res;
    }
}

void main()
{
    auto foo = new Foo!(float)();
    foo.arr = [1, 2, 3, 4];
    
    foreach (index, ref elem; foo)
    {
        elem = index + 2;
    }
    
    assert(foo.arr == [2, 3, 4, 5]);
}


Create a new paste based on this one


Comments: