www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Test the return type of 'unaryFun' and 'binaryFun'.

reply Mek101 <oidgemek101 gmail.com> writes:
As the title says, is there a way to test the return type of the 
'unaryFun' and 'binaryFun' templates from 'std.functional'?

I have the following code, and I want to to be sure that 
'predicate' returns a boolean, but neither 'is(typeof(predicate) 
== bool)' or 'is(ReturnType!predicate == bool)' seem to work.

private alias NullSized = Nullable!(size_t, size_t.max);
public NullSized indexOf(alias pred = "a == b", Range, V)(Range 
array, V value)
if((isRandomAccessRange!Range || isStaticArray!Range))
{
	alias predicate = binaryFun!pred;

	for(size_t i = 0; i < array.length; i++)
		if(predicate(array[i], value))
			return NullSized(i);
	return NullSized.init;
}
Aug 29 2019
parent reply Simen =?UTF-8?B?S2rDpnLDpXM=?= <simen.kjaras gmail.com> writes:
On Thursday, 29 August 2019 at 08:58:18 UTC, Mek101 wrote:
 As the title says, is there a way to test the return type of 
 the 'unaryFun' and 'binaryFun' templates from 'std.functional'?

 I have the following code, and I want to to be sure that 
 'predicate' returns a boolean, but neither 
 'is(typeof(predicate) == bool)' or 'is(ReturnType!predicate == 
 bool)' seem to work.

private alias NullSized = Nullable!(size_t, size_t.max);
public NullSized indexOf(alias pred = "a == b", Range, V)(Range 
array, V value)
if((isRandomAccessRange!Range || isStaticArray!Range))
{
	alias predicate = binaryFun!pred;

	for(size_t i = 0; i < array.length; i++)
		if(predicate(array[i], value))
			return NullSized(i);
	return NullSized.init;
}
You'll need to test calling the predicate with the actual types it will be processing - something like is(typeof(predicate(array[0], value)) == bool). You could (and quite possibly should) do this in the template constraint. The reason is binaryFun actually returns a generic function - a template that needs to know its actual argument types. For fun, you could actually test is(typeof(predicate!(ElementType!Range, V)) == bool). -- Simen
Aug 29 2019
parent Mek101 <oidgemek101 gmail.com> writes:
I made the following enumerations to test the predicates.

private enum bool isUnaryPredicate(alias pred, Range) = 
is(typeof(unaryFun!(pred)((ElementType!Range).init)) == bool);
private enum bool isBinaryPredicate(alias pred, Range, V) = 
is(typeof(binaryFun!(pred)((ElementType!Range).init, V.init)) == 
bool);
Both work as expected. Thank you.
Aug 29 2019