tdlp: higher-order functions

Alex Rønne Petersen xtzgzorex at gmail.com
Fri Jan 20 08:23:01 PST 2012


On 20-01-2012 17:14, Jerome BENOIT wrote:
> Hello Again:
>
> On 20/01/12 15:58, Alex Rønne Petersen wrote:
>> On 20-01-2012 15:32, Jerome BENOIT wrote:
>>> Hello List:
>>>
>>> In tDlp book in section 5.6 entitled `Higher-Order Functions. Function
>>> Literals,
>>> the first code example is:
>>>
>>> -----------------------------------------------------------------
>>> 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;
>>> }
>>> -----------------------------------------------------------------
>>>
>>> I can play it. Nevertheless, it is not clear for me right now
>>> what is the role played by `T' in the generic argument list (alias pred,
>>> T).
>>> (Its meaning is bypassed in this section via a `deduction' way.)
>>>
>>> Any hint is welcome.
>>>
>>> Thanks in advance,
>>> Jerome
>>>
>>
>> It's important to realize that D does not have generics; rather, it
>> has templates. What (alias pred, T) means is that it takes (virtually)
>> any argument as the first template parameter (function literals
>> included) and a type for the second parameter.
>>
>> You can call this function like so:
>>
>> auto ints = find!((x) { return x % 2 != 0; })([1, 2, 3, 4, 5]);
>>
>> Here, the type parameter T gets deduced from the argument, which is an
>> array of ints.
>
> I am certainly still very confused here, but I guess it is important I
> get the point before to gig further D:
> In (alias pred, T), are both `pred' and `T' parameters for the function
> find ? or is `T' some kind of parameter for `pred' ?
>
> Thanks in advance,
> Jerome
>>
>

Both pred and T are so-called template parameters. That is, they are 
statically resolved at compile time.

You could as well have called the function like so:

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

Notice how we have two parameter lists: The first one where we pass a 
function literal and the type int is the template parameter list. The 
second one is the actual runtime arguments to the function.

-- 
- Alex


More information about the Digitalmars-d-learn mailing list