www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Is this a bug?

reply Sean Eskapp <eatingstaples gmail.com> writes:
This code works fine:

	int[] arr = [ 1, 2, 3, 4, 5 ];
	auto myMax = function int(int a, int b) { return (a > b) ? a : b; };
	auto biggest = reduce!(myMax)(arr);

But passing the function literal directly to reduce causes an error. Is this
intentional?
Jan 09 2011
parent reply Christopher Nicholson-Sauls <ibisbasenji gmail.com> writes:
On 01/09/11 16:28, Sean Eskapp wrote:
 This code works fine:
 
 	int[] arr = [ 1, 2, 3, 4, 5 ];
 	auto myMax = function int(int a, int b) { return (a > b) ? a : b; };
 	auto biggest = reduce!(myMax)(arr);
 
 But passing the function literal directly to reduce causes an error. Is this
 intentional?
I believe this is because binaryFun (which reduce uses) takes a template alias parameter, which must refer to something bound -- aka, having a name. There may be a way around this, to enable using function/delegate literals, but I'm not immediately sure how or if it's needed. So, yes, it is intentional in-so-far as this is how the language feature (template alias parameters) behaves. In the meantime, you can use the string way (so long as 'a' and 'b' are your only variables): auto biggest = reduce!`(a > b) ? a : b`( arr ); Or you can use the max() function from std.algorithm if your actual use case isn't more interesting than this. -- Chris N-S
Jan 09 2011
parent "Lars T. Kyllingstad" <public kyllingen.NOSPAMnet> writes:
On Sun, 09 Jan 2011 23:09:26 -0600, Christopher Nicholson-Sauls wrote:

 On 01/09/11 16:28, Sean Eskapp wrote:
 This code works fine:
 
 	int[] arr = [ 1, 2, 3, 4, 5 ];
 	auto myMax = function int(int a, int b) { return (a > b) ? a : 
b; };
 	auto biggest = reduce!(myMax)(arr);
 
 But passing the function literal directly to reduce causes an error. Is
 this intentional?
I believe this is because binaryFun (which reduce uses) takes a template alias parameter, which must refer to something bound -- aka, having a name.
Template alias parameters do accept anonymous functions now (but I don't think it's that long ago that they didn't). This works in DMD 2.051, at least: auto biggest = reduce!((a, b) { return a > b ? a : b; })(arr); -Lars
Jan 09 2011