Skip to content

Instantly share code, notes, and snippets.

@PetarKirov
Last active September 27, 2020 18:23
Show Gist options
  • Save PetarKirov/71ccd43ea4de0421a8a3e58554c7a33b to your computer and use it in GitHub Desktop.
Save PetarKirov/71ccd43ea4de0421a8a3e58554c7a33b to your computer and use it in GitHub Desktop.
Example usage of D range primitives
module range_primitives_example;
/++
Takes a slice of the first `n` elements from `input` and advances it by the
same amount.
+/
inout(int[]) readN_version1(ref inout(int)[] input, size_t n)
{
auto result = input[0 .. n];
input = input[n .. $];
return result;
}
/++
Takes a slice of the first `n` elements from `input` and advances it by the
same amount.
Params:
Range = range type
input = range to operate on
n = number of elements to "pop" from the range
Returns:
The first `n` elements.
+/
auto readN_version2(Range)(ref Range input, size_t length)
if (Import!"std.range".isInputRange!Range)
{
import std.range : popFrontExactly, takeExactly;
auto result = input.takeExactly(length);
input.popFrontExactly(length);
return result;
}
void main()
{
import std;
{
int[] array = 20.iota.array;
writefln("The initial range is: %s", array);
const n = 5;
const headN = array.readN_version1(n);
writefln("The first %s elements are: %s", n, headN);
writefln("The rest is: %s", array);
}
"------------------".writeln;
{
int[] array = 20.iota.array;
writefln("The initial range is: %s", array);
const n = 5;
const headN = array.readN_version2(n);
writefln("The first %s elements are: %s", n, headN);
writefln("The rest is: %s", array);
}
"------------------".writeln;
{
auto doubleLinkedList = DList!int(20.iota);
auto doubleLinkedListRange = doubleLinkedList[];
writefln("The initial range is: %s", doubleLinkedList[]);
const n = 5;
auto headN = doubleLinkedListRange.readN_version2(n);
writefln("The next %s elements are: %s", n, headN);
writefln("The rest is: %s", doubleLinkedListRange);
}
}
// The self-important lookup idiom
//
// For more info see:
// https://github.com/andralex/druntime/blob/5474755677f93287d5d3de934d8b35f2b37c37fc/src/object.d#L4326
// https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1005.md
template Import(string moduleName)
{
mixin("import Import = ", moduleName, ";");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment