Two easy pieces

bearophile bearophileHUGS at lycos.com
Mon Apr 1 17:10:44 PDT 2013


This is a way to insert an item in a sorted array:


import std.stdio: writeln;
import std.range: assumeSorted;
import std.array: insertInPlace;
void main() {
     int[] arr = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90];
     int x = 35;
     arr.insertInPlace(arr.assumeSorted.lowerBound(x).length, x);
     arr.writeln;
}


Haskell has the insert/insertBy functions 
(http://zvon.org/other/haskell/Outputlist/insertBy_f.html  
http://zvon.org/other/haskell/Outputlist/insert_f.html ).
Is it worth adding such small function to std.array?

-----------------------

Sometimes you want to print something coming out of a UFCS chain 
with a formatting string. In this case you can't append the 
writef/writefln at the end of the chain. The problem is easy to 
solve with two simple functions like this. Are they worth having 
in std.stdio?


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

void ufcsWritef(T)(T data, string format) {
     writef(format, data);
}

void ufcsWritefln(T)(T data, string format) {
     writefln(format, data);
}

void main() {
     // Problem from:
     // reddit.com/r/dailyprogrammer_ideas/comments/15in89
     immutable txt = ["Line one", "Line 2"];
     foreach (i; 0 .. txt.map!q{ a.length }.reduce!max)
         txt.transversal(i).writeln;

     // Or equivalently:
     txt
     .map!q{ a.length }
     .reduce!max
     .iota
     .map!(i => txt.transversal(i))
     .ufcsWritefln("%(%s\n%)");
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list