tdlp: higher-order functions

Ali Çehreli acehreli at yahoo.com
Fri Jan 20 11:29:41 PST 2012


On 01/20/2012 08:43 AM, Jerome BENOIT wrote:

 >>>>> -----------------------------------------------------------------
 >>>>> T[] find(alias pred, T)(T[] input)
 >>>>> if (is(typeof(pred(input[0])) == bool)) {
 >>>>> for(; input.length > 0; input = input[1 .. $]) {
 >>>>> if (pred(input[0])) break;
 >>>>> }
 >>>>> return input;
 >>>>> }
 >>>>> -----------------------------------------------------------------

 > Let assume that the predicate must have now two parameters in such a way
 > that
 > the first is of type T and the second of type TM.
 >
 > auto ff = find!((x, m) { return x % m != 0; })([1, 2, 3, 4, 5]);
 >
 > Here x would be of type T, and m of type TM.
 >
 >
 > What does look the code for find then ?

We must decide on what 'm' is on the find() line above. Do you want to 
provide it as a template parameter or a function parameter? Here is how 
it could be provided as a function parameter (the last '2' in the 
parameter list):

     auto ff = find!((x, m) { return x % m != 0; })([1, 2, 3, 4, 5], 2);

And here is a matching find() function template:

T[] find(alias pred, T, TM)(T[] input, TM m)
     if (is(typeof(pred(input[0], m)) == bool))
{
     for(; input.length > 0; input = input[1 .. $]) {
         if (pred(input[0], m)) break;
     }

     return input;
}

void main()
{
     auto ff = find!((x, m) { return x % m != 0; })([1, 2, 3, 4, 5], 2);
}

Notice that pred() now takes two parameters in find().

 >
 > Thanks in advance,
 > Jerome
 >
 >>
 >

Philippe Sigaud's template document covers everything about templates:

   https://github.com/PhilippeSigaud/D-templates-tutorial

(Just download the pdf there.)

I have a chapter about templates which intentionally covers little, 
leaving the rest of templates to a later chapter:

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

The problem is, 'alias' template parameters are in that later chapter, 
which hasn't been translated yet.

Ali



More information about the Digitalmars-d-learn mailing list