Skip to content
Ranges and UFCS
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions and Ranges

D's killer feature is ranges + UFCS (Uniform Function Call Syntax). Together they make D feel like it has methods even when it doesn't.

UFCS lets you call any free function as a method:

import std.stdio, std.string;
string s = "hello";
auto upper = s.toUpper();    // same as toUpper(s)

If the first arg of a function is T, you can write t.func(args) instead of func(t, args). Every function becomes a method.

Ranges are D's iterator replacement — lazy sequences that compose:

import std.stdio, std.algorithm, std.range, std.array;

auto result = [1, 2, 3, 4, 5]
    .filter!(x => x % 2 == 0)
    .map!(x => x * x)
    .sum;
writeln(result);   // 20

filter!(), map!() etc. take a predicate as a compile-time argument (the !). They return lazy ranges — nothing computes until consumed.

The .array adaptor materializes a range into a real array if you need one.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…