const debacle

Janice Caron caron800 at googlemail.com
Sun Mar 23 06:54:43 PDT 2008


Stephen, there is another way to achieve the same thing. Instead of doing

    newArray = f(oldArray);

you can do

    auto t = f(oldArray);
    newArray = oldArray[t.first..t.second];

where t is a Pair!(int)

    struct Pair(T)
    {
        T first;
        T second;
    }

The idea here is that instead of returning an actual slice, f just
returns the indeces. Then the callee can use those indeces to take the
slice from the original array. So f would then be written something
like

    Pair!(int) f(const(char)[] array)
    {
        return Pair!(int)(1,array.length);
    }

See, now the type of the caller's array is completely unknown to the
callee, but that doesn't matter, because now it only has to return two
ints. The caller, on the other hand, gets a guarantee that f won't
modify the array, /and/ can use the returned pair to make a slice that
is guaranteed to be of exactly the right type.

(I'm not sure if Pair! exists in a standard library anywhere. If it
doesn't, it probably should).



More information about the Digitalmars-d mailing list