[Issue 4705] Redesign of std.algorithm.max()/min() + mins()/maxs()

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Feb 13 05:54:31 PST 2011


http://d.puremagic.com/issues/show_bug.cgi?id=4705



--- Comment #6 from bearophile_hugs at eml.cc 2011-02-13 05:51:55 PST ---
Two more usage examples of the improved max. This program finds the longest
common subsequence with a recursive algorithm:


import std.stdio;
T[] lcs(T)(T[] a, T[] b) {
    T[] longest(T)(T[] s, T[] t) {
        return s.length > t.length ? s : t;
    }
    if (!a.length || !b.length)
        return null;
    if (a[0] == b[0])
        return a[0] ~ lcs(a[1..$], b[1..$]);
    return longest(lcs(a, b[1..$]), lcs(a[1..$], b));
}
void main() {
    writeln(lcs("thisisatest", "testing123testing"));
}


With a key-mapping max() you are able to remove the inner function and simplify
the code (untested):

import std.stdio;
T[] lcs(T)(T[] a, T[] b) {
    if (!a.length || !b.length)
        return null;
    if (a[0] == b[0])
        return a[0] ~ lcs(a[1..$], b[1..$]);
    return max!q{a.length}([lcs(a, b[1..$]), lcs(a[1..$], b)]);
}
void main() {
    writeln(lcs("thisisatest", "testing123testing"));
}


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

This program shows the most common anagrams from a dictionary file of different
words:


import std.stdio, std.algorithm;
void main() {
    string[][string] anags;
    foreach (w; File("unixdict.txt").byLine())
        anags[w.sort.idup] ~= w.idup;
    int m = reduce!max(map!q{a.length}(anags.values));
    writeln(filter!((wl){ return wl.length == m; })(anags.values));
}


A key-mapping max() makes the code shorter and more readable (untested):


import std.stdio, std.algorithm;
void main() {
    string[][string] anags;
    foreach (w; File("unixdict.txt").byLine())
        anags[w.sort.idup] ~= w.idup;
    int m = max!q{a.length}(anags.values);
    writeln(filter!((wl){ return wl.length == m; })(anags.values));
}


maxs() simplifies the code even more (untested):

import std.stdio, std.algorithm;
void main() {
    string[][string] anags;
    foreach (w; File("unixdict.txt").byLine())
        anags[w.sort.idup] ~= w.idup;
    writeln(maxs!q{a.length}(anags.values));
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list