Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Control Flow and Functions

UFCS, Lambdas, Delegates and Variadic Functions in D

Explore D's function features: uniform function call syntax, overloading, function pointers, lambdas, delegates that capture variables, and variadic functions.

Functions in D are values: you can store them, pass them around and build new ones on the fly. Together with Uniform Function Call Syntax (UFCS), which lets you write x.f() instead of f(x), this gives D its distinctive, pipeline-style code. This lesson covers overloading, UFCS, function pointers, lambdas, delegates (closures) and variadic parameters. D code is read-only; the C stand-ins model function pointers and closures.

Overloading

Several functions can share a name if their parameter lists differ:

D
import std.stdio;

void show(int x)       { writeln("int: ", x); }
void show(double x)    { writeln("double: ", x); }
void show(string s)    { writeln("string: ", s); }

void main()
{
    show(1);        // int: 1
    show(2.5);      // double: 2.5
    show("hi");     // string: hi
}

The compiler picks the best match at compile time. Return type alone cannot distinguish overloads.

UFCS: call a function as if it were a method

If f(a, b) exists, you may write a.f(b). It works with any type, including built-in ones, and it chains cleanly:

D
import std.stdio;
import std.algorithm : map, filter, sum;
import std.array : array;

int doubled(int x) { return x * 2; }

void main()
{
    writeln(5.doubled);                       // 10
    auto result = [1, 2, 3, 4, 5, 6]
        .filter!(n => n % 2 == 0)
        .map!(n => n * n)
        .sum;
    writeln(result);                          // 56
}

Read the chain left to right: keep the even numbers (2, 4, 6), square them (4, 16, 36), add them up (56). UFCS is why much of Phobos reads like methods without the types having to define them. A true member function wins over a free function with the same name.

Function pointers and lambdas

A function pointer holds the address of a plain function:

D
int apply(int function(int) f, int x)
{
    return f(x);
}

int triple(int n) { return n * 3; }

void main()
{
    writeln(apply(&triple, 4));          // 12
    writeln(apply(n => n + 100, 4));     // 104
}

n => n + 100 is a lambda: an unnamed function. D infers its parameter and return types from context. Longer lambdas use braces: (int a, int b) { return a * b; }.

Delegates and closures

A delegate is a function pointer plus a context: the variables it needs from the scope where it was created. Writing int delegate(int) declares one. Because it carries its context, a delegate can outlive the function that made it, and the garbage collector keeps the captured variables alive:

D
int delegate(int) makeAdder(int amount)
{
    return (int x) => x + amount;       // captures amount
}

void main()
{
    auto addTen = makeAdder(10);
    auto addFive = makeAdder(5);
    writeln(addTen(1));      // 11
    writeln(addFive(1));     // 6
}

Each call to makeAdder creates its own captured amount. The captured variables live on the heap, which is why closures that escape their function need the GC (a @nogc function cannot create them). A lambda that captures nothing can convert to a plain function.

Variadic functions

A homogeneous variadic takes any number of the same type:

D
int total(int[] values...)
{
    int sum = 0;
    foreach (v; values) sum += v;
    return sum;
}

writeln(total(1, 2, 3));    // 6
writeln(total());           // 0

For mixed types use a template variadic, shown in the templates chapter: void log(T...)(T args) receives each argument with its own type.

C stand-ins: function pointers and closures

C C stand-in: function pointers like a D function parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is 12 and 104. C needs a named function where D allows an inline lambda.

C C stand-in: a closure is a function plus context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints 11 and 6: each adder keeps its own amount, which is exactly what a D closure's captured variable does. The D compiler writes this struct for you and the GC owns the context memory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does UFCS allow?

    Uniform Function Call Syntax lets any free function be called with dot syntax on its first argument.
  2. 2. What distinguishes a delegate from a function pointer?

    A delegate pairs code with a context pointer.
  3. 3. What does [1,2,3,4].filter!(n => n % 2 == 0).sum give?

    The even numbers are 2 and 4; their sum is 6.
  4. 4. Can two overloads differ only by return type?

    Overloads are selected by parameters, not return type.

Summary

  • Overloads are chosen by parameter types at compile time.
  • UFCS turns f(a, b) into a.f(b) and enables left-to-right pipelines.
  • Lambdas are anonymous functions; delegates capture surrounding variables.
  • Variadic parameters accept any number of arguments of one type (or any types via templates).

Next: Errors, exceptions and contracts