### D - std.algorithm.sorting Examples Source: https://context7.com/dlang/phobos/llms.txt Illustrates sorting and partitioning functions including `sort`, `schwartzSort`, `multiSort`, `topN`, `partition`, and `isSorted`. Requires imports from `std.algorithm.sorting`, `std.algorithm.iteration`, `std.array`, and `std.stdio`. ```d import std.algorithm.sorting; import std.algorithm.iteration : map; import std.array : array; import std.stdio; void main() { // Basic in-place sort (returns SortedRange) int[] a = [5, 3, 8, 1, 4]; sort(a); writeln(a); // [1, 3, 4, 5, 8] // Custom comparator (descending) sort!"a > b"(a); writeln(a); // [8, 5, 4, 3, 1] // schwartzSort: sort by computed key without redundant evaluation string[] words = ["banana", "kiwi", "apple", "fig"]; schwartzSort!(w => w.length)(words); writeln(words); // ["fig", "kiwi", "apple", "banana"] // multiSort: sort by multiple keys auto students = [ ["Alice", "B"], ["Bob", "A"], ["Charlie", "B"], ["Dave", "A"] ]; multiSort!("a[1] < b[1]", "a[0] < b[0]")(students); writeln(students); // [["Bob","A"],["Dave","A"],["Alice","B"],["Charlie","B"]] // topN: partially sorts so first n elements are the n smallest int[] b = [5, 3, 8, 1, 4, 2]; topN(b, 3); writeln(b[0 .. 3]); // some permutation of [1, 2, 3] // isSorted check assert(isSorted([1, 2, 3, 4])); assert(!isSorted([1, 3, 2])); // partition: split in-place by predicate int[] c = [1, 2, 3, 4, 5, 6]; auto mid = partition!(x => x % 2 == 0)(c); writeln(c); // even elements at front, odd at back (order unspecified) } ``` -------------------------------- ### D - std.algorithm.searching Examples Source: https://context7.com/dlang/phobos/llms.txt Demonstrates various searching functions like `all`, `any`, `canFind`, `count`, `find`, `findSplit`, `startsWith`, `endsWith`, `minElement`, `maxElement`, `minIndex`, `maxIndex`, and `commonPrefix`. Ensure `std.algorithm.searching` and `std.stdio` are imported. ```d import std.algorithm.searching; import std.stdio; void main() { int[] data = [3, 1, 4, 1, 5, 9, 2, 6]; // Test predicates over entire range assert(all!"a > 0"(data)); assert(any!"a > 8"(data)); // canFind with value or predicate assert(canFind(data, 5)); assert(canFind!"a > 8"(data)); // count occurrences writeln(count(data, 1)); // 2 writeln(count!"a > 4"(data)); // 3 // find returns suffix starting at match auto r = find(data, 5); writeln(r); // [5, 9, 2, 6] // findSplit splits into three parts auto parts = findSplit(data, [1, 5]); writeln(parts[0]); // [3, 1, 4] writeln(parts[1]); // [1, 5] writeln(parts[2]); // [9, 2, 6] // min/max element and index writeln(minElement(data)); // 1 writeln(maxElement(data)); // 9 writeln(minIndex(data)); // 1 writeln(maxIndex(data)); // 5 // startsWith / endsWith assert(startsWith("hello world", "hello")); assert(endsWith("hello world", "world")); // commonPrefix import std.algorithm.searching : commonPrefix; writeln(commonPrefix("parakeet", "parachute")); // para } ``` -------------------------------- ### Type Conversion with std.conv Source: https://context7.com/dlang/phobos/llms.txt Shows how to convert between different types using `to` and `parse`. Includes examples of converting to integers with different radices, handling conversion errors, and using `text` for concatenation. ```d import std.conv; import std.stdio; void main() { // to!T: convert any type to T int i = to!int("42"); double d = to!double("3.14"); string s = to!string(255); writeln(i, " ", d, " ", s); // 42 3.14 255 // to with radix int hex = to!int("FF", 16); writeln(hex); // 255 // ConvException on bad input try to!int("abc"); catch (ConvException e) writeln("Error: ", e.msg); // text(): concatenate multiple values into a string writeln(text("x=", 42, " y=", 3.14)); // x=42 y=3.14 // parse: consume from front of input range string input = "123abc"; int n = parse!int(input); writeln(n, " remaining: ", input); // 123 remaining: abc // toChars: lazy digits without allocation import std.algorithm.comparison : equal; assert(equal(toChars(42), "42")); // Hex string literal helper auto bytes = hexString!"DEADBEEF"; writeln(bytes.length); // 4 // octal literal helper writeln(octal!755); // 493 // signed / unsigned narrowing casts with overflow check writeln(signed(cast(ubyte) 200)); // -56 (wraps as byte) } ``` -------------------------------- ### Date, Time, and Duration Operations in D Source: https://context7.com/dlang/phobos/llms.txt Illustrates how to work with dates, times, and durations, including getting the current time, constructing date/time objects, performing arithmetic, and using StopWatch for benchmarking. Requires importing std.datetime, std.stdio, and core.time. ```d import std.datetime; import std.stdio; import core.time : seconds, minutes, hours, days, msecs; void main() { // Current time SysTime now = Clock.currTime(); writeln("Now: ", now); writeln("UTC: ", Clock.currTime(UTC())); // Construct Date / DateTime auto birthday = Date(1990, 6, 15); auto meeting = DateTime(2024, 6, 15, 14, 30, 0); writeln(birthday); // 1990-Jun-15 writeln(meeting); // 2024-Jun-15T14:30:00 // Arithmetic with Duration auto tomorrow = now + days(1); auto lastWeek = now - days(7); writeln("Tomorrow: ", tomorrow.toSimpleString); // Duration construction and arithmetic auto dur1 = hours(2) + minutes(30) + seconds(15); writeln(dur1.total!("seconds")); // 9015 // Date component access writeln(birthday.year, "/", birthday.month, "/", birthday.day); writeln(birthday.dayOfWeek); writeln(birthday.dayOfYear); // Interval: range of time auto interval = Interval!SysTime(now, now + days(30)); assert(interval.contains(now + days(5))); // StopWatch: benchmarking auto sw = StopWatch(AutoStart.yes); import core.thread : Thread; Thread.sleep(msecs(50)); sw.stop(); writeln("Elapsed: ", sw.peek.total!"msecs", " ms"); // Parsing ISO string auto parsed = SysTime.fromISOExtString("2024-06-15T12:00:00Z"); writeln(parsed.toISOExtString); // 2024-06-15T12:00:00Z } ``` -------------------------------- ### std.datetime — Dates, Times, and Durations Source: https://context7.com/dlang/phobos/llms.txt Provides examples for working with dates, times, and durations using the `std.datetime` module. Covers current time retrieval, construction of date/time objects, arithmetic operations, and benchmarking with `StopWatch`. ```APIDOC ## std.datetime — Dates, Times, and Durations ### std.datetime — SysTime, Date, Duration, StopWatch, Clock Key symbols: `Date`, `TimeOfDay`, `DateTime`, `SysTime`, `Clock`, `Duration`, `StopWatch`, `Interval`. ### Description This section demonstrates how to use the `std.datetime` module for handling dates, times, and durations. It includes examples for getting the current time, creating date and time objects, performing arithmetic with durations, and using `StopWatch` for benchmarking. ### Current Time #### `Clock.currTime` ```d import std.datetime; import std.stdio; SysTime now = Clock.currTime(); writeln("Now: ", now); writeln("UTC: ", Clock.currTime(UTC())); ``` ### Constructing Date and DateTime #### `Date` and `DateTime` constructors ```d import std.datetime; import std.stdio; auto birthday = Date(1990, 6, 15); auto meeting = DateTime(2024, 6, 15, 14, 30, 0); writeln(birthday); // 1990-Jun-15 writeln(meeting); // 2024-Jun-15T14:30:00 ``` ### Arithmetic with Duration #### Adding and subtracting `Duration` ```d import std.datetime; import std.stdio; import core.time : days; SysTime now = Clock.currTime(); auto tomorrow = now + days(1); auto lastWeek = now - days(7); writeln("Tomorrow: ", tomorrow.toSimpleString); ``` ### Duration Construction and Arithmetic #### `Duration` examples ```d import std.datetime; import core.time : hours, minutes, seconds; auto dur1 = hours(2) + minutes(30) + seconds(15); writeln(dur1.total!"seconds"); // 9015 ``` ### Date Component Access #### Accessing year, month, day, etc. ```d import std.datetime; import std.stdio; auto birthday = Date(1990, 6, 15); writeln(birthday.year, "/", birthday.month, "/", birthday.day); writeln(birthday.dayOfWeek); writeln(birthday.dayOfYear); ``` ### Interval: Range of Time #### `Interval` usage ```d import std.datetime; import core.time : days; SysTime now = Clock.currTime(); auto interval = Interval!SysTime(now, now + days(30)); assert(interval.contains(now + days(5))); ``` ### StopWatch: Benchmarking #### `StopWatch` usage ```d import std.datetime; import core.time : msecs; import core.thread : Thread; auto sw = StopWatch(AutoStart.yes); Thread.sleep(msecs(50)); sw.stop(); writeln("Elapsed: ", sw.peek.total!"msecs", " ms"); ``` ### Parsing ISO String #### `SysTime.fromISOExtString` ```d import std.datetime; auto parsed = SysTime.fromISOExtString("2024-06-15T12:00:00Z"); writeln(parsed.toISOExtString); // 2024-06-15T12:00:00Z ``` ``` -------------------------------- ### D std.math Module Examples Source: https://context7.com/dlang/phobos/llms.txt Demonstrates various mathematical functions and constants available in the std.math module, including algebraic, exponential, trigonometric, and rounding operations, as well as special value checks and power-of-two calculations. Requires importing std.math and std.stdio. ```d import std.math; import std.stdio; void main() { // Constants writeln(PI); // 3.14159... writeln(E); // 2.71828... writeln(SQRT2); // 1.41421... writeln(LN2); // 0.69315... // Algebraic writeln(abs(-42)); // 42 writeln(sqrt(2.0)); // 1.41421... writeln(cbrt(27.0)); // 3.0 writeln(hypot(3.0, 4.0)); // 5.0 writeln(pow(2.0, 10)); // 1024.0 // Exponential / Logarithm writeln(exp(1.0)); // 2.71828... writeln(log(E)); // 1.0 writeln(log2(1024.0)); // 10.0 writeln(log10(1000.0)); // 3.0 // Trigonometry writeln(sin(PI / 6)); // ~0.5 writeln(cos(0.0)); // 1.0 writeln(atan2(1.0, 1.0)); // PI/4 ≈ 0.7854 // Rounding writeln(ceil(1.3)); // 2.0 writeln(floor(1.9)); // 1.0 writeln(round(1.5)); // 2.0 writeln(trunc(-3.9)); // -3.0 // Special value checks assert( isNaN(real.nan)); assert( isInfinity(1.0 / 0.0)); assert(!isNaN(3.14)); assert( isFinite(3.14)); // nextPow2 / truncPow2 writeln(nextPow2(100)); // 128 writeln(truncPow2(100)); // 64 } ``` -------------------------------- ### Add New Changelog Entry Source: https://github.com/dlang/phobos/blob/master/changelog/README.md Create a new file ending in .dd in the changelog folder. The first line is the title, followed by an empty line and then the long description. Code examples can be included within the description, separated by '-------'. ```dd My fancy title of the new feature A long description of the new feature in `std.range`. It can be followed by an example: ------- import std.range : padLeft, padRight; import std.algorithm.comparison : equal; assert([1, 2, 3, 4, 5].padLeft(0, 7).equal([0, 0, 1, 2, 3, 4, 5])); assert("Hello World!".padRight('!', 15).equal("Hello World!!!!")); ------- ``` -------------------------------- ### File System Operations with std.file Source: https://context7.com/dlang/phobos/llms.txt Covers essential file system operations including reading, writing, appending, checking existence and type, getting file metadata, copying, renaming, and directory manipulation. It also demonstrates iterating through directory entries and slurping file content into typed rows. ```d import std.file; import std.stdio; import std.path : buildPath; void main() { // write and read a text file write("hello.txt", "Hello, Phobos!\n"); string content = readText("hello.txt"); writeln(content); // Hello, Phobos! // append append("hello.txt", "Second line\n"); // existence and type checks assert(exists("hello.txt")); assert(isFile("hello.txt")); // file metadata writeln("size: ", getSize("hello.txt")); // copy and rename copy("hello.txt", "hello2.txt"); rename("hello2.txt", "hello_renamed.txt"); // directory operations mkdirRecurse("mydir/sub"); write(buildPath("mydir", "sub", "data.txt"), "nested file"); assert(isDir("mydir/sub")); // dirEntries: iterate a directory tree foreach (DirEntry e; dirEntries("mydir", SpanMode.depth)) writeln(e.isDir ? "[dir] " : "[file] ", e.name); // slurp: read file into array of typed rows write("data.csv", "1 Alice\n2 Bob\n3 Charlie\n"); auto rows = slurp!(int, string)("data.csv", "%d %s"); foreach (row; rows) writefln("id=%d name=%s", row[0], row[1]); // cleanup rmdirRecurse("mydir"); remove("hello.txt"); remove("hello_renamed.txt"); remove("data.csv"); } ``` -------------------------------- ### Symbol Definitions Source: https://github.com/dlang/phobos/blob/master/etc/c/zlib/doc/algorithm.txt Defines the symbols and their corresponding bit codes used in the deflate algorithm example. These are the codes that the inflate process will decode. ```text A: 0 B: 10 C: 1100 D: 11010 E: 11011 F: 11100 G: 11101 H: 11110 I: 111110 J: 111111 ``` -------------------------------- ### Basic Output and File Operations with std.stdio Source: https://context7.com/dlang/phobos/llms.txt Demonstrates basic console output functions like writeln, write, and writefln. Also shows how to open, write to, and read from files line by line or in chunks using the File type and its associated methods. ```d import std.stdio; void main() { // Basic output writeln("Hello, World!"); write("no newline "); writefln("formatted %d", 42); // File: open, read line by line auto f = File("data.txt", "w"); f.writeln("line one"); f.writeln("line two"); f.writeln("line three"); f.close(); // Read all lines lazily foreach (line; File("data.txt").byLine) writeln("> ", line); // Read fixed-size chunks foreach (chunk; File("data.txt").byChunk(16)) writeln("chunk: ", cast(string) chunk); // lines() helper: reads entire file into array of lines import std.file : write; write("nums.txt", "10\n20\n30\n"); foreach (i, line; lines(File("nums.txt"))) writefln("line %d: %s", i, line.chomp); // readln from stdin (interactive) // string userInput = readln(); // stderr for diagnostics stderr.writeln("This goes to stderr"); // readf: formatted scan from stdin // int x; readf(" %d", x); } ``` -------------------------------- ### Table X (2 bits) Source: https://github.com/dlang/phobos/blob/master/etc/c/zlib/doc/algorithm.txt The second-level lookup table, referenced from the first table. This table handles symbols that start with '110' and are longer than 3 bits. ```text 00: C,1 01: C,1 10: D,2 11: E,2 ``` -------------------------------- ### Printf-style Formatting with std.format Source: https://context7.com/dlang/phobos/llms.txt Illustrates using `format`, `sformat`, and `formattedWrite` for creating formatted strings. Covers format specifiers for width, precision, fill, and different bases, as well as parsing formatted strings with `formattedRead`. ```d import std.format; import std.array : appender; import std.stdio; void main() { // format: returns a newly allocated string string s = format("Hello, %s! You are %d years old.", "Alice", 30); writeln(s); // Hello, Alice! You are 30 years old. // format specifiers: width, precision, fill writeln(format("%10d", 42)); // " 42" writeln(format("% -10s|", "left")); // "left |" writeln(format("%08.2f", 3.14)); // "00003.14" writeln(format("%x", 255)); // "ff" writeln(format("%X", 255)); // "FF" writeln(format("%b", 12)); // "1100" // format arrays and structs writeln(format("%s", [1, 2, 3])); // [1, 2, 3] // sformat: write into a provided char buffer (no allocation) char[64] buf; auto filled = sformat(buf[], "pi = %.4f", 3.14159); writeln(filled); // pi = 3.1416 // formattedWrite: write to any output range (e.g., Appender) auto app = appender!string; formattedWrite(app, "(%d, %d)", 10, 20); writeln(app.data); // (10, 20) // formattedRead: parse values from a formatted string string input = "name=Bob age=25"; string name; int age; formattedRead(input, "name=%s age=%d", name, age); writeln(name, " is ", age); // Bob is 25 } ``` -------------------------------- ### Table Y (3 bits) Source: https://github.com/dlang/phobos/blob/master/etc/c/zlib/doc/algorithm.txt Another second-level lookup table, referenced from the first table. This table handles symbols that start with '111' and are longer than 3 bits. ```text 000: F,2 001: F,2 010: G,2 011: G,2 100: H,2 101: H,2 110: I,3 111: J,3 ``` -------------------------------- ### Dlang Data Parallelism with std.parallelism Source: https://context7.com/dlang/phobos/llms.txt Illustrates parallel processing of arrays using foreach, lazy mapping, and reduction operations with std.parallelism. Also shows manual task creation and custom TaskPool usage. ```d import std.parallelism; import std.algorithm.iteration : map; import std.math : sqrt; import std.range : iota; import std.array : array; import std.stdio; void main() { // parallel foreach: process array items across CPU cores auto data = iota(1, 9).array; auto results = new double[data.length]; foreach (i, ref val; parallel(data)) results[i] = sqrt(cast(double) val); writeln(results); // taskPool.map: parallel lazy map auto arr = iota(0, 10_000).array; auto sums = taskPool.map!(x => x * x)(arr); writeln(sums[0 .. 5]); // [0, 1, 4, 9, 16] // taskPool.reduce: parallel reduction auto total = taskPool.reduce!"a + b"(0.0, arr.map!(x => cast(double) x)); writeln("sum = ", total); // 49995000.0 // Manual task with future/promise pattern auto t = task!(() => 6 * 7)(); taskPool.put(t); writeln("6 * 7 = ", t.yieldForce); // 42 // Custom TaskPool with explicit thread count auto pool = new TaskPool(4); scope(exit) pool.finish(true); foreach (i; pool.parallel(iota(5).array)) writeln("processing ", i); } ``` -------------------------------- ### std.algorithm.searching Source: https://context7.com/dlang/phobos/llms.txt Provides functions for searching ranges, including checking for element existence, counting occurrences, finding elements, splitting ranges, and determining if a range starts or ends with a specific sequence. ```APIDOC ## std.algorithm.searching — Find, Count, and Test Elements ### Description Functions for searching ranges: `all`, `any`, `canFind`, `count`, `find`, `findSplit`, `startsWith`, `endsWith`, `minElement`, `maxElement`, `minIndex`, `maxIndex`, and more. ### Usage Examples ```d import std.algorithm.searching; import std.stdio; void main() { int[] data = [3, 1, 4, 1, 5, 9, 2, 6]; // Test predicates over entire range assert(all!("a > 0")(data)); assert(any!("a > 8")(data)); // canFind with value or predicate assert(canFind(data, 5)); assert(canFind!("a > 8")(data)); // count occurrences writeln(count(data, 1)); // 2 writeln(count!("a > 4")(data)); // 3 // find returns suffix starting at match auto r = find(data, 5); writeln(r); // [5, 9, 2, 6] // findSplit splits into three parts auto parts = findSplit(data, [1, 5]); writeln(parts[0]); // [3, 1, 4] writeln(parts[1]); // [1, 5] writeln(parts[2]); // [9, 2, 6] // min/max element and index writeln(minElement(data)); // 1 writeln(maxElement(data)); // 9 writeln(minIndex(data)); // 1 writeln(maxIndex(data)); // 5 // startsWith / endsWith assert(startsWith("hello world", "hello")); assert(endsWith("hello world", "world")); // commonPrefix import std.algorithm.searching : commonPrefix; writeln(commonPrefix("parakeet", "parachute")); // para } ``` ``` -------------------------------- ### Dlang Concurrency with std.concurrency Source: https://context7.com/dlang/phobos/llms.txt Demonstrates spawning a worker thread, sending typed messages, and receiving replies using std.concurrency. Includes named thread registration and lookup. ```d import std.concurrency; import std.conv : text; import std.stdio; // Worker function: runs in its own thread static void worker(Tid owner) { // Receive typed messages via pattern matching bool running = true; while (running) { receive( (int n) { send(owner, text("Got int: ", n)); }, (string s) { if (s == "quit") running = false; else send(owner, text("Got string: ", s)); } ); } } void main() { Tid tid = spawn(&worker, thisTid); // Send messages to the worker send(tid, 42); send(tid, "hello"); send(tid, "quit"); // Receive replies (with timeout for safety) import core.time : msecs; foreach (_; 0 .. 2) { receiveTimeout(msecs(1000), (string reply) { writeln(reply); } ); } // Got int: 42 // Got string: hello // Named thread registration register("printer", thisTid); Tid found = locate("printer"); assert(found == thisTid); } ``` -------------------------------- ### Preview Pending Changelog Source: https://github.com/dlang/phobos/blob/master/changelog/README.md To preview the changelog locally, clone the 'tools' and 'dlang.org' repositories and run the 'pending_changelog' make target. ```bash make -C ../dlang.org -f posix.mak pending_changelog ``` -------------------------------- ### String Manipulation with std.string Source: https://context7.com/dlang/phobos/llms.txt Demonstrates various string manipulation functions including stripping whitespace, finding substrings, chomping/chopping strings, justification, and character translation. Also includes C interop helpers for string conversion. ```d import std.string; import std.stdio; void main() { string s = " Hello, World! "; // strip whitespace writeln(strip(s)); // "Hello, World!" writeln(stripLeft(s)); // "Hello, World! " writeln(stripRight(s)); // " Hello, World!" // indexOf / lastIndexOf writeln(indexOf("hello world", "world")); // 6 writeln(lastIndexOf("abcabc", "bc")); // 4 // chomp / chop writeln(chomp("hello\n")); // "hello" writeln(chop("hello")); // "hell" // center / leftJustify / rightJustify writeln(center("hi", 10)); // " hi " writeln(leftJustify("hi", 10, '-')); // "hi--------" writeln(rightJustify("hi", 10, '-')); // "--------hi" // translate: character-by-character substitution table string from = "aeiou"; string to = "AEIOU"; writeln(translate("hello world", makeTrans(from, to))); // hEllO wOrld // tr: POSIX-style character translation/deletion writeln(tr("Hello World", "a-z", "A-Z")); // HELLO WORLD writeln(tr("hello 123", "0-9", "", "d")); // hello (delete digits) // wrap: word-wrap long text string text = "The quick brown fox jumps over the lazy dog"; writeln(wrap(text, 20)); // The quick brown fox // jumps over the lazy // dog // C interop helpers import core.stdc.string : strlen; const(char)* cstr = toStringz("hello"); writeln(fromStringz(cstr)); // hello } ``` -------------------------------- ### Dlang Comparison Functions Source: https://context7.com/dlang/phobos/llms.txt Illustrates element-wise range equality (equal), finding minimum (min) and maximum (max) values, clamping a value within bounds (clamp), checking membership in a set (among), calculating edit distance (levenshteinDistance), finding the first differing pair in ranges (mismatch), and lexicographic comparison (cmp). Requires importing std.algorithm.comparison. ```d import std.algorithm.comparison; import std.stdio; void main() { // equal: element-wise equality (works on any ranges) assert(equal([1, 2, 3], [1, 2, 3])); assert(!equal([1, 2], [1, 2, 3])); // min / max of multiple values writeln(min(3, 1, 4, 1, 5)); // 1 writeln(max(3, 1, 4, 1, 5)); // 5 // clamp: bound a value within [lo, hi] writeln(clamp(10, 0, 5)); // 5 writeln(clamp(-3, 0, 5)); // 0 writeln(clamp(2, 0, 5)); // 2 // among: check if value is in a set assert(among(3, 1, 2, 3, 4)); // levenshteinDistance: edit distance between strings writeln(levenshteinDistance("kitten", "sitting")); // 3 // mismatch: find first differing pair auto pair = mismatch([1, 2, 3, 4], [1, 2, 9, 4]); writeln(pair[0].front, " vs ", pair[1].front); // 3 vs 9 // cmp: lexicographic comparison, returns negative/0/positive assert(cmp([1, 2, 3], [1, 2, 4]) < 0); assert(cmp("abc", "abc") == 0); } ``` -------------------------------- ### Dlang std.range Functions Source: https://context7.com/dlang/phobos/llms.txt Demonstrates common range manipulation functions like iota, take, drop, chain, zip, enumerate, retro, stride, chunks, cycle, repeat, only, slide, and tee. Requires importing std.range and potentially other modules for specific operations. ```d import std.range; import std.algorithm.iteration : map; import std.array : array; import std.stdio; void main() { // iota: lazy numeric sequence writeln(iota(5).array); // [0, 1, 2, 3, 4] writeln(iota(1, 10, 2).array); // [1, 3, 5, 7, 9] // take / drop writeln(iota(100).take(5).array); // [0, 1, 2, 3, 4] writeln(iota(10).drop(7).array); // [7, 8, 9] // chain: concatenate ranges writeln(chain([1, 2], [3, 4], [5]).array); // [1, 2, 3, 4, 5] // zip: pair elements from multiple ranges auto pairs = zip([1, 2, 3], ["a", "b", "c"]).array; writeln(pairs); // [Tuple!(1,"a"), Tuple!(2,"b"), Tuple!(3,"c")] // enumerate: (index, value) pairs foreach (i, v; enumerate(["x", "y", "z"])) writefln("%d: %s", i, v); // 0:x, 1:y, 2:z // retro: reverse traversal writeln(retro([1, 2, 3, 4]).array); // [4, 3, 2, 1] // stride: every Nth element writeln(stride(iota(10), 3).array); // [0, 3, 6, 9] // chunks: split into fixed-size sub-ranges writeln(chunks([1,2,3,4,5,6,7], 3).array); // [[1,2,3],[4,5,6],[7]] // cycle: infinite circular range writeln(cycle([1, 2, 3]).take(8).array); // [1,2,3,1,2,3,1,2] // repeat / only writeln(repeat(0, 4).array); // [0, 0, 0, 0] writeln(only(10, 20, 30).array); // [10, 20, 30] // slide: sliding window writeln(slide(iota(6), 3).array); // [[0,1,2],[1,2,3],[2,3,4],[3,4,5]] // tee: observe a range without consuming it import std.algorithm.iteration : each; int sum = 0; auto logged = tee!(x => sum += x)(iota(5)); writeln(logged.array); // [0,1,2,3,4] writeln("sum=", sum); // sum=10 } ``` -------------------------------- ### Dlang Array Utility Functions Source: https://context7.com/dlang/phobos/llms.txt Covers materializing ranges into dynamic arrays (array), efficient incremental string building (appender), concatenating ranges with a separator (join), splitting strings by delimiters (split), replacing substrings (replace, replaceFirst), and repeating sequences (replicate). Also demonstrates building associative arrays from key-value pairs (assocArray) and iterating them (byPair). Requires importing std.array and potentially std.range. ```d import std.array; import std.algorithm.iteration : map, filter; import std.stdio; void main() { // array(): materialize any range into a dynamic array auto squares = map!(x => x * x)([1, 2, 3, 4, 5]).array; writeln(squares); // [1, 4, 9, 16, 25] // appender: efficient incremental building auto app = appender!string(); app.put("Hello"); app.put(", "); app.put("World"); writeln(app.data); // Hello, World // appender with pre-existing array auto numApp = appender([1, 2, 3]); numApp ~= 4; numApp.put([5, 6]); writeln(numApp.data); // [1, 2, 3, 4, 5, 6] // join: concatenate range of ranges with separator string[] words = ["one", "two", "three"]; writeln(words.join(", ")); // one, two, three // split writeln("a,b,c".split(",")); // ["a", "b", "c"] writeln("hello world".split()); // ["hello", "world"] (whitespace) // replace / replaceFirst writeln("aaabbbccc".replace("bbb", "XXX")); // aaaXXXccc writeln("aaabbbbbbaaa".replaceFirst("bb", "X")); // aaaXbbbbaaa // replicate writeln("ab".replicate(3)); // ababab writeln([1, 2].replicate(3)); // [1, 2, 1, 2, 1, 2] // assocArray: build AA from key/value ranges import std.range : zip; string[] keys = ["a", "b", "c"]; int[] vals = [1, 2, 3]; auto aa = assocArray(zip(keys, vals)); writeln(aa); // ["a":1, "b":2, "c":3] // byPair: iterate an AA as (key, value) tuples foreach (pair; aa.byPair) writeln(pair.key, " => ", pair.value); } ``` -------------------------------- ### Path String Manipulation with std.path Source: https://context7.com/dlang/phobos/llms.txt Provides utilities for OS-safe path manipulation, including building paths, extracting components (basename, dirname, extension), modifying extensions, checking path validity (absolute/relative), and performing glob-style pattern matching. ```d import std.path; import std.stdio; void main() { // buildPath: OS-safe path joining writeln(buildPath("usr", "local", "bin", "dmd")); // usr/local/bin/dmd (Posix) // component extraction string p = "/home/user/docs/readme.txt"; writeln(baseName(p)); // readme.txt writeln(dirName(p)); // /home/user/docs writeln(extension(p)); // .txt writeln(stripExtension(p)); // /home/user/docs/readme // setExtension / withExtension writeln(setExtension("file.txt", ".md")); // file.md // validation assert(isAbsolute("/usr/bin")); assert(!isAbsolute("relative/path")); // relativePath writeln(relativePath("/home/user/docs/a.txt", "/home/user")); // docs/a.txt // pathSplitter: iterate components foreach (part; pathSplitter("/usr/local/bin")) write("[", part, "]"); writeln(); // [/][usr][local][bin] // globMatch: shell-style wildcards assert(globMatch("hello.d", "*.d")); assert(globMatch("path/to/file.txt", "**/*.txt")); assert(!globMatch("hello.d", "*.c")); // isValidPath / isValidFilename assert(isValidFilename("report_2024.pdf")); } ``` -------------------------------- ### Runtime and Compile-time Regex Operations in D Source: https://context7.com/dlang/phobos/llms.txt Demonstrates various regex operations including matching, capturing groups, replacement, and splitting using both runtime and compile-time regex. Requires importing std.regex, std.stdio, and std.array. ```d import std.regex; import std.stdio; import std.array : array; void main() { // Runtime regex auto r = regex(`\d+`); // matchFirst: find first match auto m = matchFirst("Order #1042 and #2099", r); if (!m.empty) writeln("First number: ", m.hit); // 1042 // matchAll: iterate all matches foreach (c; matchAll("Order #1042 and #2099", r)) writeln(c.hit); // 1042, then 2099 // Capture groups auto dateRe = regex(`(\d{4})-(\d{2})-(\d{2})`); auto date = matchFirst("Today is 2024-06-15", dateRe); writeln("Year: ", date[1], " Month: ", date[2], " Day: ", date[3]); // replaceFirst / replaceAll with string or delegate writeln(replaceAll("foo bar baz", regex(`\b\w`), m => m.hit.toUpper)); // Foo Bar Baz // split by regex writeln(split("one1two2three", regex(`\d`)).array); // ["one","two","three"] // Compile-time regex (faster, native code) enum ctr = ctRegex!(`^[a-z]+$`); assert(!matchFirst("hello", ctr).empty); assert(matchFirst("Hello123", ctr).empty); // Named captures auto namedRe = regex(`(?P\w+)@(?P\w+\.\w+)`); auto email = matchFirst("contact@example.com", namedRe); writeln(email["user"]); // contact writeln(email["domain"]); // example.com } ``` -------------------------------- ### Dlang Lazy Iteration Functions Source: https://context7.com/dlang/phobos/llms.txt Demonstrates lazy transformation (map), predicate filtering (filter), left-folding with a seed (fold), summation (sum), mean calculation, eager side-effect execution (each), grouping consecutive elements (group), flattening ranges (joiner), and cumulative folding (cumulativeFold). Requires importing std.algorithm.iteration and other relevant modules. ```d import std.algorithm.iteration; import std.array : array; import std.stdio; void main() { int[] data = [1, 2, 3, 4, 5, 6, 7, 8]; // map: lazy transform auto doubled = map!(x => x * 2)(data); writeln(doubled.array); // [2, 4, 6, 8, 10, 12, 14, 16] // filter: lazy predicate filter auto evens = filter!(x => x % 2 == 0)(data); writeln(evens.array); // [2, 4, 6, 8] // fold: left-fold with initial seed auto total = fold!((a, b) => a + b)(data, 0); writeln(total); // 36 // sum: accurate numeric summation writeln(sum(data)); // 36 // mean writeln(mean(data)); // 4 (integer division) // each: eager side-effect per element each!(x => write(x, " "))(data); writeln(); // 1 2 3 4 5 6 7 8 // group: consecutive equal elements as (value, count) tuples int[] runs = [1, 1, 2, 3, 3, 3, 2]; import std.typecons : tuple; writeln(group(runs).array); // [Tuple!(1,2), Tuple!(2,1), Tuple!(3,3), Tuple!(2,1)] // joiner: flatten range of ranges lazily auto sentences = ["hello world", "foo bar"]; import std.algorithm.iteration : splitter; auto words = sentences.map!(s => s.splitter(' ')).joiner; writeln(words.array); // ["hello","world","foo","bar"] // cumulativeFold: running totals writeln(cumulativeFold!((a, b) => a + b)(data).array); // [1,3,6,10,15,21,28,36] } ```