The syntax of sort and templates

Patrick Schluter via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 26 05:10:09 PDT 2017


On Friday, 26 May 2017 at 09:59:26 UTC, zakk wrote:
> Hello everyone,
>
> I just started using D and I am a bit puzzled by the syntax of 
> the sort function is std.algorithm.sorting, which is
>
> sort!(comparingFunction)(list)
>
> where comparingFunction is often a lambda expression. For 
> instance in the Wolfram Language the equivalent function is
>
> Sort[list,comparingFunction]
>
> My questions are:
>
> 1) Why is D making using of the binary ! operator, which as far 
> as I understand introduces a template?

! here indicates where the template parameter start in a template 
invocation

templatename!(compile time parameter)(runtime parameter)

>
> 2) Why is a template needed here?

The template allows to generate the code so that the comparison 
is known at compile time and can be optimised properly. If you 
look for example in C, where sorting is done via the qsort() 
function. The comparison function must be provided by a function 
pointer. This means that the qsort function must call a function 
for doing even the simplest comparison. Furthermore, this call is 
indirect which on some processors can not be predicted and takes 
an inordinary long time to run.
Another nuisance associated with qsort and function pointer in C 
is that you have to define a specific function, with a specific 
name doing the type conversions because qsort only works with 
void * as parameter. This makes it slow, cumbersome and error 
prone.
All these defaults are inexistant in D thanks to the template, 
which take the lambda, i.e. an anonymous function, which is 
defined with the right types and inserts it in the sort code as 
if it had been written by hand.
The template replaces the macro preprocessor of C, but at more 
profound and intimate language level.

>
> 3) It seems to me like the argument passed to the template is a 
> lambda expression. I only know about templates taking types as 
> argument. What's going on?

That's the strength of D that templates are not limited to types. 
Almost anything can be templatized which opens possibilities that 
other languages don't even start to be able to conceive.

>
> Many thanks!




More information about the Digitalmars-d-learn mailing list