The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
D
1
Print a literal string on standard output
writeln("Hello world!");
Alternative implementation:
pragma(msg, "Hello World");
2
Loop to execute some code a constant number of times
foreach(i; 0..10)
  writeln("Hello");
Alternative implementation:
iota(0,10).each!(a => "Hello".writeln);
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
void finish() {
	writeln("I' m a done job");
}
4
Create a function which returns the square of an integer
int square(int x) {
   return x*x;
}
Alternative implementation:
alias fun = (int a){return a * a;};
5
Declare a container type for two floating-point numbers x and y
struct Point{
    double x;
    double y;
}

    
Alternative implementation:
class Point
{
    float x;
    float y;
}
6
Do something with each item x of an array-like collection items, regardless indexes.
foreach(x; items) {
	doSomethingWith(x);
}
Alternative implementation:
items.each!(a => writeln(a))();
7
Print each index i with its value x from an array-like collection items
foreach(i, x; items)
{
   writefln("%s: %s", i, x);
}
Alternative implementation:
items.enumerate.each!(a => writeln("i = ", a[0], " value = ", a[1]));
8
Create a new map object x, and provide some (key, value) pairs as initial content.
int[string] x = ["one": 1, "two": 2];
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
struct BinaryTree(T)
{
	T data;
	BinaryTree* left;
	BinaryTree* right;
}
10
Generate a random permutation of the elements of list x
randomShuffle(x);
11
The list x must be non-empty.
x.randomSample(1);
12
Check if the list contains the value x.
list is an iterable finite container.
bool here = canFind(items, x);
13
Access each key k with its value x from an associative array mymap, and print them.
int[string] mymap = ["Hello":1 , "World":2];
foreach (k, v; mymap)
    writeln("Key: ", k, " Value: ", v);
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
real pick(real _a, real _b){
    return uniform(_a, _b);
}
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
auto x1 = uniform(a, b+1);
auto x2 = uniform!"[]"(a, b);
16
Call a function f on every node of binary tree bt, in depth-first infix order
void btTraversal(T)(BinaryTree!T bt, void function(T) f) {
    if (bt.left)
        btTraversal(*(bt.left), f);

    f(bt.data);

    if (bt.right)
        btTraversal(*(bt.right), f);
}
17
The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.
struct Node(T){
    Node[] children;
    T data;
}

alias TreeOfIntegers = Node!(int);
18
Call a function f on every node of a tree, in depth-first prefix order
void prefixOrderTraversal(alias f)(ref Tree tree)
{
	f(tree);
	foreach (child; tree.children)
		prefixOrderTraversal!f(child);
}
19
Reverse the order of the elements of list x.
This may reverse "in-place" and destroy the original ordering.
reverse(x);
Alternative implementation:
auto y = x.retro;
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
auto search(int[][] m, int x)
{
	foreach (i, row; m)
	{
		foreach (j, cell; row)
		{
			if (cell == x)
				return tuple(i, j);
		}
	}
}
21
Swap the values of the variables a and b
auto temp = a;
a = b;
b = temp;
Alternative implementation:
swap(a,b);
22
Extract the integer value i from its string representation s (in radix 10)
auto i = s.to!int;
23
Given a real number x, create its string representation s with 2 decimal digits following the dot.
string str = format("%.2s", x);
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
string s = "ネコ";
25
Share the string value "Alan" with an existing running process which will then display "Hello, Alan"
auto t = spawn( {
   receive( (string s) { writefln("Hello, %s", s); } );
} );

t.send("Alan");
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
auto x = new double[][](m, n);
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
auto x = new real[][][](m, n, p);
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
sort!("a.p < b.p")(items);
29
Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.
items = items.remove(i);
30
Launch the concurrent execution of procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
taskPool.amap!f(iota(1, 1001));
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
uint factorial(in uint n) pure nothrow @nogc
in {
    assert(n <= 12);
} body {
    if (n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
uint exp(uint x, uint n) {
    if(n == 0)
        return 1;
    if(n == 1)
        return x;
    if(n % 2 == 0)
        return exp(x * x, n / 2);
    else
        return x * exp(x * x, (n - 1) / 2);
}
33
Assign to the variable x the new value f(x), making sure that no other thread may modify x between the read and the write.
synchronized x = f(x);
34
Declare and initialize a set x containing unique objects of type T.
auto x = redBlackTree!T;
35
Implement a function compose (A -> C) with parameters f (A -> B) and g (B -> C), which returns composition function g ∘ f
auto compose(f, g) {
	return std.functional.compose!(f, g);
}
36
Implement a function compose which returns composition function g ∘ f for any functions f and g having exactly 1 parameter.
auto _compose(T)(T function(T) f, T function(T) g)
{
    auto lambda = (T x) { return g(f(x));  };
    return lambda;
}
37
Transform a function that takes multiple arguments into a function for which some of the arguments are preset.
int add(int n1, int n2)
{
    return n1 + n2;
}

alias add5 = curry!(add, 5);
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
auto t = s[i .. j];
39
Set boolean ok to true if string word is contained in string s as a substring, or to false otherwise.
bool ok = s.canFind(word);
40
Declare a Graph data structure in which each Vertex has a collection of its neighbouring vertices.
struct Vertex
{
	float x, y, z;
	Vertex* [] adjacentVertices;
}
41
Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
auto t = s.retro.array;
42
Print each item v of list a which is not contained in list b.
For this, write an outer loop to iterate on a and an inner loop to iterate on b.
auto a = [1,2,3,4,5];
auto b = [3,5];

void main()
{
mainloop:
	foreach(v;  a){
		foreach(w; b){
			if(v == w) continue mainloop;
		}
		writeln(v);		 
	}
}
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
outer:
foreach (i; 0 .. m.length)
{
	foreach (j; 0 .. m[i].length)
	{
		if (m[i][j] < 0)
		{
			writeln(m[i][j]);
			break outer;
		}
	}
}
44
Insert element x at position i in list s. Further elements must be shifted to the right.
s.insertInPlace(i, x);
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
Thread.sleep(5.seconds);
46
Create string t consisting of the 5 first characters of string s.
Make sure that multibyte characters are properly handled.
string t = s[0..5];
47
Create string t consisting in the 5 last characters of string s.
Make sure that multibyte characters are properly handled.
string t = s[$-5..$];
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
auto s = "One,
Two,
Three
";
Alternative implementation:
auto s = `line1
line2
line3`;
Alternative implementation:
auto s = r"line1
line2
line3";
49
Build list chunks consisting in substrings of input string s, separated by one or more space characters.
auto chunks = s.splitter;
50
Write a loop that has no end clause.
while (true) { }
Alternative implementation:
for (;;) {}
51
Determine whether the map m contains an entry for the key k
if (k in m) { }
52
Determine whether the map m contains an entry with the value v, for some key.
m.byValue.canFind(v);
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
string y = x.join(", ");
54
Calculate the sum s of the integer list or array x.
auto s = x.sum();
55
Create the string representation s (in radix 10) of the integer value i.
string s = i.to!string;
56
Fork-join : launch the concurrent execution of procedure f with parameter i from 1 to 1000.
Tasks are independent and f(i) doesn't return any value.
Tasks need not run all at the same time, so you may use a pool.
Wait for the completion of the 1000 tasks and then print "Finished".
foreach(i; parallel(iota(1,1001))){
	f(i);
}
writeln("Finished");
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
auto y = [1, 2, 3, 4, 5].filter!(a => a%2==0);
Alternative implementation:
auto y = x.filter!(p);
58
Create string lines from the content of the file with filename f.
string lines = cast(string) read(f, size_t.max);
Alternative implementation:
auto lines = f.readText;
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
stderr.writeln(x, " is negative");
60
Assign to x the string value of the first command line parameter, after the program name.
auto x = args[1];
61
Assign to variable d the current date/time value, in the most standard type.
auto d = Clock.currTime;
62
Set i to the first position of string y inside string x, if exists.

Specify if i should be regarded as a character index or as a byte index.

Explain the behavior when y is not contained in x.
auto i = x.countUntil(y);
63
Assign to x2 the value of string x with all occurrences of y replaced by z.
Assume occurrences of y are not overlapping.
auto x2 = x.replace(y,z);  
64
Assign to x the value 3^247
BigInt x = BigInt(3);
x ^^= 247;
65
From the real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"
string percent = format("%.1f%%", x * 100.0);
66
Calculate the result z of x power n, where x is a big integer and n is a positive integer.
BigInt z = x ^^ n;
67
Calculate binom(n, k) = n! / (k! * (n-k)!). Use an integer type able to handle huge numbers.
BigInt binom(uint n, uint k)
{
   assert(n >= k);
   BigInt r = 1;
   for(uint i = 0; i <= k; ++i)
   {
      r *= n-i;
      r /= i+1;
   }
   return r;
}
68
Create an object x to store n bits (n being potentially large).
BitArray x;
x.length = n;
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
auto s = 8;
auto gen = Random(s);
writeln(gen.front);
70
Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
auto rng = Random(cast(uint)Clock.currTime.stdTime);
Alternative implementation:
rndGen.seed(cast(uint)Clock.currTime.stdTime);
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
void main(string[] args)
{
	args[1..$].join(" ").writeln;
}
Alternative implementation:
void main(string[] args)
{
	writeln(args.dropOne.joiner(" "));
}
73
Create a factory named fact for any sub class of Parent and taking exactly one string str as constructor parameter.
auto fact(T, A...)(A a)
if (is(T==class) && is(T: Parent))
{
    return new T(a);
}
74
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
x = gcd(a, b);
Alternative implementation:
BigInt gcd(in BigInt x, in BigInt y) pure {
    if (y == 0)
        return x;
    return gcd(y, x%y);
}

gcd(a, b);
75
Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.
uint x = (a * b) / gcd(a, b);
76
Create the string s of integer x written in base 2.

E.g. 13 -> "1101"
auto s = to!string(x,2);
77
Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.
auto x = complex(-2, 3);
x * complex(0, 1);
78
Execute a block once, then execute it again as long as boolean condition c is true.
do
{
    something;
    somethingElse;
}
while (c);
79
Declare the floating point number y and initialize it with the value of the integer x .
int x;
float y = to!float(x);
// or
float y = cast(float) x;
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
int y = cast(int)x;
81
Declare integer y and initialize it with the rounded value of floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
int y = cast(int) x.round;
82
Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.
auto occurrences = s.count(t);
83
Declare regular expression r matching strings "http", "htttp", "httttp", etc.
auto r = regex("htt+p");
84
Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2
auto c = bitSet(i).length;
85
Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

An overflow may be above the max positive value, or below the min negative value.
bool addingWillOverflow(int x, int y)
{
    bool result;
    core.checkedint.adds(x, y, result);
    return result;
}
86
Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

An overflow may be above the max positive value, or below the min negative value.
bool multiplyWillOverflow(int x, int y)
{
    bool result;
    core.checkedint.muls(x, y, result);
    return result;
}
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
exit(0);
88
Create a new bytes buffer buf of size 1,000,000.
void[] buf = malloc(1024 * 1024)[0..1024 * 1024];
Alternative implementation:
void[] buf = GC.malloc(1024 * 1024)[0..1024 * 1024];
89
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
throw new Exception("invalid value for x (%s) in '%s'".format(x, __PRETTY_FUNCTION__));
Alternative implementation:
void foo(int x)
in
{
    assert(x != 0, "wrong value for x");
}
body
{
    // function
}
90
Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.
struct Foo
{
    private int _x;
    int x() {return _x;}
}
91
Read from the file data.json and write its content into the object x.
Assume the JSON data is suitable for the type of x.
JSONValue x = "data.json".readText.parseJSON;

struct User {
    int age;
    string name;

    this(JSONValue user) {
        age  = user["age"];
        name = user["name"];
    }
}

auto user = User(x);
92
Write the contents of the object x into the file data.json.
auto x = JSONValue(["age":42, "name":"Bob"]);
"data.json".write(x.toJSON);
93
Implement procedure control which receives one parameter f, and runs f.
void control(alias f)()
if (isCallable!f)
{
    f();
}
Alternative implementation:
void control(void function() f)
{
    f();
}
94
Print the name of the type of x. Explain if it is a static type or dynamic type.

This may not make sense in all languages.
writeln(typeid(x));
95
Assign to variable x the length (number of bytes) of the local file at path.
auto x = getSize(path);
96
Set boolean b to true if string s starts with prefix prefix, false otherwise.
b = s.startsWith(prefix);
97
Set boolean b to true if string s ends with string suffix, false otherwise.
b = s.endsWith(suffix);
98
Convert a timestamp ts (number of seconds in epoch-time) to a date with time d. E.g. 0 -> 1970-01-01 00:00:00
auto d = SysTime(unixTimeToStdTime(ts), UTC());
99
Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.
string x = Date(1993, 10, 26).toISOExtString;
100
Sort elements of array-like collection items, using a comparator c.
items.sort!c;
101
Make an HTTP request with method GET to URL u, then store the body of the response in string s.
string s = u.get.to!string;
102
Make an HTTP request with method GET to URL u, then store the body of the response in file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.
download(u, "result.txt");
103
Read from the file data.xml and write its contents into the object x.
Assume the XML data is suitable for the type of x.
XmlArchive archive = new XmlArchive!(char);
archive.doc.parse(read("data.xml"));
Serializer ser = new Serializer(archive);
ser.deserialize(x);
104
Write the contents of the object x into the file data.xml.
auto archive = new XmlArchive!(char);
auto serializer = new Serializer(archive); 
serializer.serialize(x);
write("data.xml", archive.data);
105
Assign to the string s the name of the currently executing program (but not its full path).
void main(string[] args) {
    string s = args[0].baseName;
}
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
string dir = absolutePath;
107
Assign to string dir the path of the folder containing the currently running executable.
(This is not necessarily the working directory, though.)
void main(string[] args) {
    string dir = args[0].dirName;
}
108
Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)
int x = 42;

void printIfDefined(alias name)()
{
    import std.stdio: writeln;
    static if( __traits(compiles, writeln(mixin(name))))
        writeln(mixin(name));
}

void main(string[] args)
{
    printIfDefined!"x";
    printIfDefined!"Foo.bar";
}
Alternative implementation:
static if (is(typeof(x = x.init)))
    writeln(x);
109
Set n to the number of bytes of a variable t (of type T).
auto n = T.sizeof;
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
bool blank = s.all!isSpace;
111
From current process, run program x with command-line parameters "a", "b".
spawnProcess([x, "a", "b"]);
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
mymap.byKeyValue
     .array
     .sort!((a, b) => a.key < b.key)
     .each!(p => writeln(p.key, " ", p.value));
113
Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.
mymap.byKeyValue
     .array
     .sort!((a, b) => a.value < b.value)
     .each!(p => writeln(p.key, " ", p.value));
114
Set boolean b to true if objects x and y contain the same values, recursively comparing all referenced elements in x and y.
Tell if the code correctly handles recursive types.
b = deeplyEqual(x, y));
115
Set boolean b to true if date d1 is strictly before date d2 ; false otherwise.
bool b = d1 < d2;
116
Remove all occurrences of string w from string s1, and store the result in s2.
auto s2 = s1.replace(w, "");
117
Set n to the number of elements of the list x.
auto n = x.length;
Alternative implementation:
n = walkLength(x);
118
Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.
bool[typeof(x[0])] y;

foreach (e ; x)
    y[e] = true;
Alternative implementation:
auto y = redBlackTree(x);
119
Remove duplicates from the list x.
Explain if the original order is preserved.
x = x.sort.uniq.array;
Alternative implementation:
x = redBlackTree(x)[].array;
120
Read an integer value from the standard input into the variable n
readf("%d", &n);
121
Listen UDP traffic on port p and read 1024 bytes into buffer b.
ubyte[1024] b;

auto sock = new UdpSocket();
scope(exit) sock.close;

sock.bind(new InternetAddress(p));
sock.receive(b);
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
enum Suit{
  SPADES,
  HEARTS,
  DIAMONDS,
  CLUBS
}
123
Verify that predicate isConsistent returns true, otherwise report assertion violation.
Explain if the assertion is executed even in production environment or not.
assert(isConsistent);
124
Write the function binarySearch which returns the index of an element having the value x in the sorted array a, or -1 if no such element exists.
long binarySearch(long[] a, long x) {
    long result = a.assumeSorted.lowerBound(x).length;
    if (result == a.length || a[result] != x)
        return -1;
    return result;
}
125
measure the duration t, in nanoseconds, of a call to the function foo. Print this duration.
StopWatch sw;
sw.start;
foo;
auto t = sw.peek.nsecs; 
writeln(t);
126
Write a function foo that returns a string and a boolean value.
auto foo()
{
    return tuple("theString", true);
}
127
Import the source code for the function foo body from a file "foobody.txt".
void foo()
{
    mixin(import("foobody.txt"));
}
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if      (c1) f1;
else if (c2) f2;
else if (c3) f3;
132
Run procedure f, and return the duration of the execution of f.
auto elapsed = benchmark!f(1)[0].msecs;
Alternative implementation:
{
    import std.stdio;
    auto mt = measureTime!((TickDuration a{writeln(a.msecs);});
    f();
}
Alternative implementation:
StopWatch sw;
sw.start;
f();
auto elapsed = sw.peek;
133
Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn't match, or to false otherwise.
ok = indexOf(word, s, CaseSensitive.no) != -1;
134
Declare and initialize a new list items, containing 3 elements a, b, c.
auto items = [a, b, c];
135
Remove at most 1 item from list items, having value x.
This will alter the original list or return a new list, depending on which is more idiomatic.
If there are several occurrences of x in items, remove only one of them. If x is absent, keep items unchanged.
items = items.remove(items.countUntil!(a => a == x));
136
Remove all occurrences of value x from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
items = items.filter!(a => a != x).array;
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
bool b = s.filter!(a => !isDigit(a)).empty;
Alternative implementation:
bool b = s.all!isDigit;
138
Create a new temporary file on the filesystem.
auto f = File.tmpfile();
139
Create a new temporary folder on filesystem, for writing.
string mkTmpDir()
{
    import std.uuid, std.file, std.path;
    string d = buildPath(tempDir, randomUUID.toString);
    if (!d.exists)
    {
        mkdir(d);
        return d;
    }
    else return null;
}

string s;
while (!s.length)
  s = mkTmpDir;
140
Delete from map m the entry having key k.

Explain what happens if k is not an existing key in m.
m.remove(k);
141
Iterate in sequence over the elements of the list items1 then items2. For each iteration print the element.
chain(items1, items2).each!writeln;
142
Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"
s = to!string(x, 16);
Alternative implementation:
s = format("%x", x);
143
Iterate alternatively over the elements of the list items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.
roundRobin(items1, items2).each!writeln;
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
bool b = fp.exists;
145
Print message msg, prepended by current date and time.

Explain what behavior is idiomatic: to stdout or stderr, and what the date format is.
log(msg);
146
Extract floating point value f from its string representation s
float f = s.to!float;
147
Create string t from string s, keeping only ASCII characters
auto t = s.filter!(a => a.isASCII).array;
148
Read a list of integer numbers from the standard input, until EOF.
auto list = stdin.byLine.map!(a => a.to!int);
149
As an exception, this content is not under license CC BY-SA 3.0 like the rest of this website.
 
150
Remove last character from string p, if this character is a slash /.
auto p = "no_more_slashes///".stripRight!(a => a == '/');
writeln(p); // no_more_slashes
Alternative implementation:
p=p.chomp("/");
151
Remove last character from string p, if this character is the file path separator of current platform.

Note that this also transforms unix root path "/" into the empty string!
p = p.chomp(dirSeparator);
152
Create string s containing only the character c.
string s = to!string(c);
153
Create the string t as the concatenation of the string s and the integer i.
string t = s ~ to!string(i);
Alternative implementation:
string t = "%s%d".format(s, i);
154
Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.
string c = roundRobin(c1.dropOne.chunks(2), c2.dropOne.chunks(2))
    .map!(a => a.to!int(16)).array
    .chunks(2)
    .map!(a => ((a[0] + a[1]) / 2))
    .fold!((a,b) => a ~= "%.2X".format(b))("#");
155
Delete from filesystem the file having path filepath.
try
    remove(filepath);
catch (FileException fe)
    writeln(fe.msg);
156
Assign to the string s the value of the integer i in 3 decimal digits. Pad with zeros if i < 100. Keep all digits if i1000.
string s = format("%03d", i);
157
Initialize a constant planet with string value "Earth".
const string planet = "Earth";
Alternative implementation:
immutable string planet = "Earth";
Alternative implementation:
static immutable string planet = "Earth";
Alternative implementation:
enum planet = "Earth";
Alternative implementation:
enum string planet = "Earth";
158
Create a new list y from randomly picking exactly k elements from list x.

It is assumed that x has at least k elements.
Each element must have same probability to be picked.
Each element from x must be picked at most once.
Explain if the original ordering is preserved or not.
auto y = randomSample(x, k);
159
Define a Trie data structure, where entries have an associated value.
(Not all nodes are entries)
struct Trie
{
    Rune c;
    Trie*[Rune] children;
    bool isEntry;
    bool value;
}
160
Execute f32() if platform is 32-bit, or f64() if platform is 64-bit.
This can be either a compile-time condition (depending on target) or a runtime detection.
version(X86)
    f32();
version(X86_64)
    f64();
Alternative implementation:
static if (size_t.sizeof == 4)
    f32();
static if (size_t.sizeof == 8)
    f64();
161
Multiply all the elements of the list elements by a constant c
elements[] *= c;
162
execute bat if b is a program option and fox if f is a program option.
void main(string[] args)
{
    void bat(){} void fox(){}
    getopt(args, "b", &bat, "f", &fox);
}
163
Print all the list elements, two by two, assuming list length is even.
list.chunks(2).each!writeln;
164
Open the URL s in the default browser.
Set boolean b to indicate whether the operation was successful.
browse(s);
165
Assign to variable x the last element of list items.
int[42] items;
int x = items[$-1];
Alternative implementation:
int[] items;
auto x = items.back();
166
Create the list ab containing all the elements of the list a, followed by all the elements of the list b.
int[] a, b;
auto ab = a ~ b;
Alternative implementation:
int[] a, b;
auto ab = chain(a, b);
167
Create string t consisting of string s with its prefix p removed (if s starts with p).
string t = s.chompPrefix(p);
168
Create string t consisting of string s with its suffix w removed (if s ends with w).
string t = s.chomp(w);
169
Assign to integer n the number of characters of string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
size_t n = s.length;
Alternative implementation:
size_t n = s.walkLength;
Alternative implementation:
size_t n = s.byGrapheme.walkLength;
170
Set n to the number of elements stored in mymap.

This is not always equal to the map capacity.
const n = mymap.length;
171
Append element x to the list s.
s ~= x;
172
Insert value v for key k in map m.
m[k] = v;
173
Number will be formatted with a comma separator between every group of thousands.
string f = "%3,d".format(123456);
174
Make a HTTP request with method POST to URL u
auto response = post(u, content);
175
From array a of n bytes, build the equivalent hex string s of 2n digits.
Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).
s = a.toHexString;
176
From hex string s of 2n digits, build the equivalent array a of n bytes.
Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).
ubyte[] a = s.chunks(2)
             .map!(digits => digits.to!ubyte)
             .array;
Alternative implementation:
ubyte[] a = cast(ubyte[]) hexString!s.representation;
177
Construct a list L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory D and all it's subdirectories.
immutable exts = ["jpg", "jpeg", "png"];
auto L = D.dirEntries(SpanMode.depth)
          .map!(to!string)
          .filter!(f => exts.canFind(f.split(".")[$-1]));
178
Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise.
Describe if the edges are considered to be inside the rectangle.
bool b = x1<x && x<x2 && y1<y && y<y2;
179
Return the center c of the rectangle with coördinates(x1,y1,x2,y2)
auto c = tuple((x1+x2)/2, (y1+y2)/2);
180
Create list x containing the contents of directory d.

x may contain files and subfolders.
No recursive subfolder listing.
auto x = dirEntries(d, SpanMode.shallow);
189
Produce a new list y containing the result of function T applied to all elements e of list x that match the predicate P.
y = x.filter!(P).map!(T);
196
Given an integer array a of size n, pass the first, third, fifth and seventh, ... up to the m th element to a routine foo which sets all these elements to 42.
void foo(Range)(Range r) {
	r.fill(42);
}

foo(a.indexed(iota(0,m,2)));
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
string foo = environment.get("FOO", "none");
224
Insert element x at the beginning of list items.
items = x ~ items;