Returning multiple arrays from function - struct or byref the only option?
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Oct 15 10:14:29 PDT 2014
On Wednesday, 15 October 2014 at 16:48:24 UTC, Laeeth Isharc
wrote:
> Hi.
>
> I have to write a bunch of functions that operate on input
> arrays to return multiple output arrays.
>
> In case helpful the inputs are price bars or economic data
> points (datetime, ohlc) and the outputs are nx1 arrays (I won't
> say vectors) of doubles or structs.
>
> What is the best way to return multiple arrays in this kind of
> situation. In Python I returned a tuple of numpy arrays, and
> the C way would be to pass a pointer to the return
> destinations, and I guess I could do the same in a D way by
> passing by ref not value).
>
> I see that I can return a struct containing dynamic arrays, and
> return it (by value of course). I have read the forum
> discussion a while back over how to return multiple values, and
> tried using tuples. I don't see that I can return a tuple of
> arrays - am I missing something?
>
> Here is a simple case. Can I do better ?
>
> Thanks.
>
>
> import std.typecons;
> import std.stdio;
>
> struct RetStruct
> {
> double[] a;
> double[] b;
> }
>
> RetStruct myfunction(double x)
> {
> RetStruct s;
> double[] a,b;
> a~=x+1.0;
> a~=x+9.0;
> b~=x+2.0;
> b~=x+11.0;
> s.a=a;
> s.b=b;
> return s;
> }
>
> void main()
> {
> writefln("%s",myfunction(99.0));
> }
You could also return an std.typecons.Tuple containing both
arrays. http://dlang.org/phobos/std_typecons.html#.Tuple
More information about the Digitalmars-d-learn
mailing list