Partial return type specification

bearophile bearophileHUGS at lycos.com
Sun Oct 3 13:48:54 PDT 2010


This post is probably silly, so feel free to ignore it :-)

As function return type I am able to use the correct type, as in the bar() function below, or 'auto' that's a Jolly that works for any type, and is useful when the type is very complex:


import std.algorithm: map, equal;

/* Range!int */ auto foo() {
    return map!("a * a")([1, 2, 3, 4]);
}

/* Range!int */ int[] bar() {
    return [1, 2, 3, 4];
}

void main() {
    assert(equal(foo(), [1, 4, 9, 16]));
    assert(equal(bar(), [1, 2, 3, 4]));
}


But in some situations I've felt the need of something intermediate, like a way to say that the output of the function is an iterable of int values (instead of strings or floats), like a Range!int.

Even using this annotation, the actual return type of the function foo() doesn't change, it's still a map!(), so the Range!int acts just like the generic "auto", the difference is that the compiler gives a compile error if the result isn't an iterable of ints.

So I am talking about something like (this doesn't compile because I think you can't use 'auto' with functions with a out() contract):


import std.algorithm: map, equal;
import std.traits: ForeachType, Unqual;

auto foo()
    out(result) {
        static assert(is(Unqual!(ForeachType!(typeof(result))) == int));
    }
    body {
        return map!("a * a")([1, 2, 3, 4]);
    }

void main() {
    assert(equal(foo(), [1, 4, 9, 16]));
}


Bye,
bearophile


More information about the Digitalmars-d mailing list