returning different types via function

bearophile bearophileHUGS at lycos.com
Wed Nov 20 02:03:53 PST 2013


Meta:

> import std.typecons;
>
> Nullable!(string[]) func(string[] zz) pure nothrow
> {
> 	return Nullable!(string[])();
> }
>
> void main()
> {
>         //AssertError thrown for trying to get
>         //a value that is null. Might as well
>         //return null at this point
> 	auto x = func(["test"]) ~ ["test"];
> }



This code doesn't throw, so the behavour is different:

string[] func(string[] zz) pure nothrow {
      return []; // This calls the runtime!
}
void main() {
      auto x = func(["test"]) ~ ["test"];
}


In this case you are saying that an empty string[] is a correct
output for func, while in the case with Nullable you are saying
that it can't return an empty result.

But I agree that the design of a language like Whiley is better,
with its Flow Typing:
http://whiley.org/guide/typing/flow-typing/

In such case Whiley forces you to analyse the return of func(),
and after the analysis the type of such return value changes
according to if the branch you are seeing. So exceptions happen,
and less programmer mistakes.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list