Thread overview
Average function using Variadic Functions method
Nov 02, 2021
pascal111
Nov 02, 2021
rikki cattermole
Nov 02, 2021
pascal111
Nov 02, 2021
Mike Parker
Nov 02, 2021
Ali Çehreli
November 02, 2021

I'm programming average calculating function by using Variadic Functions method, but I didn't get yet what is the wrong in my code:

// D programming language

import std.stdio;
import core.vararg;
import std.conv;

float foo(...)
{

float x=0;

for(int i=0; i<_arguments.length; ++i){

x+=to!float(_arguments[i]);

}

x/=_arguments.length;

return x;

}

int main()
{

writeln(foo(2,3));

return 0;

}

November 03, 2021
You probably don't want to be using C variadics.

Instead try the typed one:

float mean(float[] input...) {
	// you don't want to divide by zero
	if (input.length == 0)
		return 0;

	float temp = 0;
	// floats and double initialize to NaN by default, not zero.
	
	foreach(value; input) {
		temp += value;
	}

	return temp / input.length;
}
November 02, 2021
On Tuesday, 2 November 2021 at 16:29:07 UTC, rikki cattermole wrote:
> You probably don't want to be using C variadics.
>
> Instead try the typed one:
>
> float mean(float[] input...) {
> 	// you don't want to divide by zero
> 	if (input.length == 0)
> 		return 0;
>
> 	float temp = 0;
> 	// floats and double initialize to NaN by default, not zero.
> 	
> 	foreach(value; input) {
> 		temp += value;
> 	}
>
> 	return temp / input.length;
> }

"input..." seems nice, where can I get more information about it?
November 02, 2021
On Tuesday, 2 November 2021 at 16:35:40 UTC, pascal111 wrote:

>
> "input..." seems nice, where can I get more information about it?

"Typesafe variadic functions"

https://dlang.org/spec/function.html#typesafe_variadic_functions

November 02, 2021
On 11/2/21 9:35 AM, pascal111 wrote:

> "input..." seems nice, where can I get more information about it?

I include most of the language in this free book:

  http://ddili.org/ders/d.en/index.html

which has an Index Section that I find useful to locate information:

  http://ddili.org/ders/d.en/ix.html

I searched for '...' in that page and was happy that one of the candidates was "..., function parameter" which took me here:


<http://ddili.org/ders/d.en/parameter_flexibility.html#ix_parameter_flexibility....,%20function%20parameter>

Note: I've heard before that the links are broken but it works for me. (I enclosed the link with <> to help with it.)

Ali