Comment #0 by bearophile_hugs — 2010-08-29T15:31:21Z
In Python I use very often the * (__mul__) list operator, it's handy in many situations (it is not lazy):
>>> "abc" * -1
''
>>> "abc" * 0
''
>>> "abc" * 1
'abc'
>>> "abc" * 5
'abcabcabcabcabc'
>>> [0] * 5
[0, 0, 0, 0, 0]
It's not a good idea to add a similar product operator to D arrays because despite vector mult operation will probably require [] (while the mul doesn't require it), the two are too much syntactically close, they risk being too much bug-prone.
So I suggest to simply add this mul() to std.array (this must be eager, not a lazy range, otherwise it's not handy for its purposes):
/// ...
T[] mul(T)(T[] items, int times) {
T[] result;
static if(!is( typeof(items) == void[] )) {
if (times > 0 && items.length > 0) {
if (items.length == 1) {
result.length = times;
result[] = items[0];
} else {
result.length = items.length * times;
for (size_t pos; pos < result.length; pos += items.length)
result[pos .. pos+items.length] = items;
}
}
}
return result;
}
// demo ----------
import std.stdio;
void main() {
auto a1 = [0].mul(10);
writeln(a1);
auto a2 = [0, 5, 10].mul(4);
writeln(a2);
}
More unittests and a ddoct on request.
Comment #1 by bearophile_hugs — 2010-08-29T15:44:13Z
This mul() needs more work, to be used on const arrays too. If you are interested, I may try to write this improvement.
If the given array is one of the string types, it has to call std.string.repeat() inside.
But the second argument of std.string.repeat() must become a signed integer, otherwise you just need repeat("ab", -1) to create a crash.
Comment #2 by bearophile_hugs — 2010-09-01T14:35:02Z
Isn't this adequately covered by `std.array.replicate`?
Comment #4 by cauterite — 2016-08-19T22:33:34Z
Surely this issue can be closed now.
As has been said already, replicate does pretty much exactly what is proposed here.
Comment #5 by greeenify — 2016-08-20T12:09:10Z
I am closing this as replicate seems to do exactly what you was asked for. Vector operations are out of scope anyways and require a uniform interface.
Feel free to reopen of you disagree.