On Sat, 30 Oct 2010 23:00:59 -0400
bearophile <bearophileh...@lycos.com> wrote:

> - Keep in mind that ~ and ~= in arrays isn't a very fast operation. In some 
> cases an Appender helps, and in some cases some workaround may be needed.

A use case of join (in std.string) is indeed to build a text from snippets.
But I personly use this func most often to build a text representation of list 
of elements of any kind. For this, join falls short:
* no auto-conversion to string
* no delimiters
Thus, I think the following may be useful in the stdlib (aside join):

=================================================
string listText(T)(T[] elements, string sep) {
    uint l = elements.length ;
    if (l == 0)
        return "" ;
    string[] texts ; texts.length = l ;
    foreach (uint i, T element ; elements)
        texts[i] = to!string(elements[i]) ;
    return join(texts, sep) ;
}
string listText(T)(T[] elements, string sep, string leftDelim, string 
rightDelim) {
    return format("%s%s%s", leftDelim, listText(elements, sep), rightDelim) ;
}

// testing
struct Symbol {
    string k;
    int v;
    string toString () {
        return format("%s:%s", this.k, to!string(this.v)) ;
    }
}

void main () {
    int[] ints = [1,2,3] ;
    writeln(listText(ints , "---")) ;
    writeln(listText(ints , " " , "(",")")) ;
    Symbol[3] symbols = [Symbol("a",1) , Symbol("b",2) , Symbol("c",3)] ;
    writeln(listText(symbols , " | " , "{ "," }")) ;
}

// writes:
1---2---3
(1 2 3)
{ a:1 | b:2 | c:3 }
==========================================

This works sensibly with any custom type where toString is defined. (else you 
get the type name ;-)

I would also love a mapping-func param, to allow expressing things like 
listText(ints, square, " "); but without optional parameters (AFAIK), 
combinations are problematic.

Also, I could not find functional methods like map, filter, reduce in 
std.functional. Where else? Also not in std.array. Map would be handy above to 
string-ify. And remove the need for a map func param in listText (I would be 
happy to contribute them if someone guides me on how to participate.)


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com

Reply via email to