Brace expansion: Difference between revisions

+ D entry
(depythonized)
(+ D entry)
Line 325:
 
=={{header|C++}}==
 
C++11 solution:
 
Line 501 ⟶ 500:
return 0;
}</lang>
 
=={{header|D}}==
{{trans|Python}}
This code is not UTF-corrected, because it uses slicing instead of front, popFront, etc.
<lang d>import std.stdio, std.typecons, std.array, std.range, std.algorithm,
std.string;
 
Nullable!(Tuple!(string[], string)) getGroup(string s, in uint depth) {
string[] sout;
auto comma = false;
 
while (!s.empty) {
// (const g, s) = getItems(s, depth);
const r = getItems(s, depth);
const g = r[0];
s = r[1];
 
if (s.empty)
break;
sout ~= g;
 
if (s.front == '}') {
if (comma)
return typeof(return)(tuple(sout, s[1 .. $]));
return typeof(return)(tuple(
sout.map!(a => '{' ~ a ~ '}').array, s[1 .. $]));
}
 
if (s[0] == ',') {
comma = true;
s = s[1 .. $];
}
}
return typeof(return)();
}
 
Tuple!(string[], string) getItems(string s, in uint depth=0) {
auto sout = [""];
 
while (!s.empty) {
auto c = s[0 .. 1];
if (depth && (c == "," || c == "}"))
return tuple(sout, s);
 
if (c == "{") {
const x = getGroup(s.dropOne, depth + 1);
if (!x.isNull) {
// cartesianProduct(sout), x[0])
string[] outTmp;
foreach (const a; sout)
foreach (const b; x[0])
outTmp ~= a ~ b;
sout = outTmp;
s = x[1];
continue;
}
}
 
if (c == "\\" && s.length > 1) {
c ~= s[1];
s = s[1 .. $];
}
 
sout = sout.map!(a => a ~ c).array;
s = s[1 .. $];
}
return tuple(sout, s);
}
 
void main() {
immutable testCases = r"~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
a{b{1,2}c
a{1,2}b}c
a{1,{2},3}b
a{b{1,2}c{}}
more{ darn{ cowbell,},}
ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr
{a,{\,b}c
a{b,{{c}}
{a{\}b,c}d
{a,b{{1,2}e}f";
 
foreach (const s; testCases.splitLines)
writefln("%s\n%-( %s\n%)\n", s, s.getItems[0]);
}</lang>
{{out}}
<pre>~/{Downloads,Pictures}/*.{jpg,gif,png}
~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
 
It{{em,alic}iz,erat}e{d,}, please.
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
 
{,{,gotta have{ ,\, again\, }}more }cowbell!
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
 
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
 
a{b{1,2}c
a{b1c
a{b2c
 
a{1,2}b}c
a1b}c
a2b}c
 
a{1,{2},3}b
a1b
a{2}b
a3b
 
a{b{1,2}c{}}
a{b1c{}}
a{b2c{}}
 
more{ darn{ cowbell,},}
more darn cowbell
more darn
more
 
ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr
abcqr
abd\,efqr
abd\,eg\hqr
abi\,jknqr
abi\,jl\,mnqr
abo\,pqr
 
{a,{\,b}c
{a,{\,b}c
 
a{b,{{c}}
a{b,{{c}}
 
{a{\}b,c}d
{a\}bd
{acd
 
{a,b{{1,2}e}f
{a,b{1e}f
{a,b{2e}f
</pre>
 
=={{header|Haskell}}==