Thread overview
Can You Expand Arrays into an Argument List?
May 15, 2020
surlymoor
May 15, 2020
H. S. Teoh
May 15, 2020
Dennis
May 15, 2020
surlymoor
May 15, 2020
Hello,

I don't often miss JS, but one particular feature that I enjoyed is the ability to expand arrays into argument lists using a unary operator.

Example: add(...[1, 1]) === add(1, 1) // IIRC

I've been looking in Phobos and the spec, but nothing's popped out to me. Is there a fairly obvious alternative to this, or am I going to have to experiment with some templates and mixins? (Not that I mind, btw, D's metaprogramming is very fun.)

With thanks,
sm
May 15, 2020
On Fri, May 15, 2020 at 06:44:52PM +0000, surlymoor via Digitalmars-d-learn wrote: [...]
> I don't often miss JS, but one particular feature that I enjoyed is the ability to expand arrays into argument lists using a unary operator.
> 
> Example: add(...[1, 1]) === add(1, 1) // IIRC
> 
> I've been looking in Phobos and the spec, but nothing's popped out to me. Is there a fairly obvious alternative to this, or am I going to have to experiment with some templates and mixins? (Not that I mind, btw, D's metaprogramming is very fun.)
[...]

It's possible to do it, but the called function has to support it. If that's not an option, then you're out of luck and probably have to use metaprogramming instead.  Here's how to do it:

	int add(int[] args...) {
		... // access `args` here as an array
	}

	void main() {
		int[] arr = [ 1, 2, 3 ];
		add(arr);
		add(1, 2);
		add(1, 3, 4, 5, 7);
	}


T

-- 
Recently, our IT department hired a bug-fix engineer. He used to work for Volkswagen.
May 15, 2020
On Friday, 15 May 2020 at 19:19:59 UTC, H. S. Teoh wrote:
> Here's how to do it:
>
> 	int add(int[] args...) {
> 		... // access `args` here as an array
> 	}

Beware that that language feature, typesafe variadic functions, might become deprecated:
https://github.com/dlang/dmd/pull/11124
May 15, 2020
On Friday, 15 May 2020 at 19:19:59 UTC, H. S. Teoh wrote:
> It's possible to do it, but the called function has to support it. If that's not an option, then you're out of luck and probably have to use metaprogramming instead.  Here's how to do it:
>
> 	int add(int[] args...) {
> 		... // access `args` here as an array
> 	}
>
> 	void main() {
> 		int[] arr = [ 1, 2, 3 ];
> 		add(arr);
> 		add(1, 2);
> 		add(1, 3, 4, 5, 7);
> 	}
>
>
> T

Unfortunately, this isn't applicable to my situation, but I'm thankful nevertheless for the information. It would be nice if such an expansion were more universal in its applicability, but I'm not a language designer.

With thanks,
sm