www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 13594] New: std.algorithm.nextPermutation for fixed size

https://issues.dlang.org/show_bug.cgi?id=13594

          Issue ID: 13594
           Summary: std.algorithm.nextPermutation for fixed size arrays
                    too
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody puremagic.com
          Reporter: bearophile_hugs eml.cc

This is correct code:

void main() {
    import std.stdio: writeln;
    import std.algorithm: nextPermutation;
    int[] a = [1, 2, 3];
    do {
        a.writeln;
    } while (a.nextPermutation);
}



In many cases in my code the number of items to permute is known at
compile-time, so for both memory efficiency and to not throw away precious
compile-time knowledge of the array length, I'd like to permute a fixed-length
array too:


void main() {
    import std.stdio: writeln;
    import std.algorithm: nextPermutation;
    int[3] a = [1, 2, 3];
    do {
        a.writeln;
    } while (a.nextPermutation);
}


But this is refused by dmd 2.067apha:

test.d(7,15): Error: template std.algorithm.nextPermutation cannot deduce
function from argument types !()(int[3]), candidates are:
...\dmd2\src\phobos\std\algorithm.d(13186,6):       
std.algorithm.nextPermutation(alias less = "a<b", BidirectionalRange)(ref
BidirectionalRange range) if (isBidirectionalRange!BidirectionalRange &&
hasSwappableElements!BidirectionalRange)



And even slicing (a common workaround for silly Phobos functions that force me
to throw away the compile-time knowledge of the array length) can't be used
because nextPermutation takes its argument by reference:


void main() {
    import std.stdio: writeln;
    import std.algorithm: nextPermutation;
    int[3] a = [1, 2, 3];
    do {
        a.writeln;
    } while (a[].nextPermutation);
}


test.d(7,17): Error: template std.algorithm.nextPermutation cannot deduce
function from argument types !()(int[]), candidates are:
...\dmd2\src\phobos\std\algorithm.d(13186,6):       
std.algorithm.nextPermutation(alias less = "a<b", BidirectionalRange)(ref
BidirectionalRange range) if (isBidirectionalRange!BidirectionalRange &&
hasSwappableElements!BidirectionalRange)


So I'd like nextPermutation to accept a fixed-size array, because there's
nothing in a permutation algorithm that requires it to have run-time length of
its random-access input. Alternatively, I'd like nextPermutation to take the
dynamic array by value (and not mutate the length but only the contents
positions with swaps).

--
Oct 10 2014