On 1/19/23 19:11, Ruby The Roobster wrote:

>      typeof(c).stringof.writeln;

> The program prints:
>
> ["a", "b", "c", "d", "e"]
> Result
>
> What is the purpose of this 'Result' type?

Just to make sure, 'Result' is what the programmer of a Phobos algorithm chose to name a struct type. It could be anything.

I will try to demonstrate it by naming my struct 'MyResult' below. The following range algorithm alternates between the two values it is called with.

The pragma(msg) inside 'main' prints MyResult.

auto alternate(T)(T a, T b) {
    // This function will return an object
    // of the following nested struct.
    // (Note: This is for demonsration
    // purposes only. Yes, this can be
    // be more optimal.)
    struct MyResult {
        bool useB = false;

        enum empty = false; // Infinite

        T front() {
            return useB ? b : a;
        }

        void popFront() {
            // Flip the selector
            useB = !useB;
        }
    }

    // Here, an object of the struct is
    // returned. It has single member (useB)
    // that it uses as a selector.
    // The values 'a' and 'b' are the actual
    // function arguments.
    return MyResult();
}

import std;

void main() {
    auto myRange = alternate(42, 7);

    // This prints 'MyResult' at compile time
    pragma(msg, typeof(myRange));

    const expected = [ 42, 7, 42, 7, 42 ];
    assert(myRange.take(5).equal(expected));
}

> even when the type
> has the same inherent function:

Different instantiations of templates are distinct types. For example, if I called 'alternate' with two 'long' values, both alternate!int (as instantiated by the code above) and alternate!long would have different MyResult struct types.

Although they would have the same functionality, they would be compiled potentially with very different CPU instructions and would not be assignable.

Ali

Reply via email to