Two easy pieces

ixid nuaccount at gmail.com
Mon Apr 1 19:28:30 PDT 2013


On Tuesday, 2 April 2013 at 00:10:45 UTC, bearophile wrote:
> 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

UFCS also needs its write function to be able to print whatever 
data it is passed and then pass exactly the data it was passed on 
so you can drop write statements into UFCS chains and take them 
out without needing to chop around the chain.

auto result = 
data.dostuff.domorestuff.writeUFCS.morestuff.finalstep;


More information about the Digitalmars-d-learn mailing list