Brace expansion: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(10 intermediate revisions by 4 users not shown)
Line 4:
 
 
;Task
{{task heading}}
 
Write a function that can perform brace expansion on any input string, according to the following specification.<br>
Line 273:
:* &nbsp; [[Brace_expansion_using_ranges]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F getitem(=s, depth = 0)
V out = [‘’]
L s != ‘’
Line 332 ⟶ 331:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|AppleScript}}==
 
This may seem like a cheat, but it ''is'' a legitimate and obvious way to tackle the problem with AppleScript in the unlikely event that the need should arise. It adjusts the escape levels in the input text, feeds it as a shell script to macOS's sh shell, and lets ''it'' handle the expansion.
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
Line 393 ⟶ 391:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}*)</pre>
 
=={{header|AutoHotkey}}==
 
<syntaxhighlight lang="autohotkey">;This one is a lot more simpler than the rest
BraceExp(string, del:="`n") {
Loop, Parse, string
Line 425 ⟶ 422:
rosettacode
rosettastone</pre>
 
=={{header|C}}==
Handles only properly formed input.
<syntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 761 ⟶ 757:
gotta have more cowbell!
gotta have\, again\, more cowbell!</pre>
 
=={{header|C++}}==
C++11 solution:
 
<syntaxhighlight lang=cpp>#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
 
namespace detail {
 
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end)
{ }
template <typename Lambda>
bool next(Lambda istoken)
{
if (_tbegin == _end) {
return false;
}
_tbegin = _tend;
for (; _tend != _end && !istoken(*_tend); ++_tend) {
if (*_tend == '\\' && std::next(_tend) != _end) {
++_tend;
}
}
if (_tend == _tbegin) {
_tend++;
}
return _tbegin != _end;
}
ForwardIterator begin() const { return _tbegin; }
ForwardIterator end() const { return _tend; }
bool operator==(char c) { return *_tbegin == c; }
};
 
template <typename List>
void append_all(List & lista, const List & listb)
{
if (listb.size() == 1) {
for (auto & a : lista) {
a += listb.back();
}
} else {
List tmp;
for (auto & a : lista) {
for (auto & b : listb) {
tmp.push_back(a + b);
}
}
lista = std::move(tmp);
}
}
 
template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{
std::vector<List> alts{ { String() } };
while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {
if (token == '{') {
append_all(alts.back(), expand<String, List>(token));
} else if (token == ',') {
alts.push_back({ String() });
} else if (token == '}') {
if (alts.size() == 1) {
for (auto & a : alts.back()) {
a = '{' + a + '}';
}
return alts.back();
} else {
for (std::size_t i = 1; i < alts.size(); i++) {
alts.front().insert(alts.front().end(),
std::make_move_iterator(std::begin(alts[i])),
std::make_move_iterator(std::end(alts[i])));
}
return std::move(alts.front());
}
} else {
for (auto & a : alts.back()) {
a.append(token.begin(), token.end());
}
}
}
List result{ String{ '{' } };
append_all(result, alts.front());
for (std::size_t i = 1; i < alts.size(); i++) {
for (auto & a : result) {
a += ',';
}
append_all(result, alts[i]);
}
return result;
}
 
} // namespace detail
 
template <
typename ForwardIterator,
typename String = std::basic_string<
typename std::iterator_traits<ForwardIterator>::value_type
>,
typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
detail::tokenizer<ForwardIterator> token(begin, end);
List list{ String() };
while (token.next([](char c) { return c == '{'; })) {
if (token == '{') {
detail::append_all(list, detail::expand<String, List>(token));
} else {
for (auto & a : list) {
a.append(token.begin(), token.end());
}
}
}
return list;
}
 
template <
typename Range,
typename String = std::basic_string<typename Range::value_type>,
typename List = std::vector<String>
>
List expand(const Range & range)
{
using Iterator = typename Range::const_iterator;
return expand<Iterator, String, List>(std::begin(range), std::end(range));
}
 
int main()
{
for (std::string string : {
R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
R"(It{{em,alic}iz,erat}e{d,}, please.)",
R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
R"(a{b{1,2}c)",
R"(a{1,2}b}c)",
R"(a{1,{2},3}b)",
R"(a{b{1,2}c{}})",
R"(more{ darn{ cowbell,},})",
R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
R"({a,{\,b}c)",
R"(a{b,{{c}})",
R"({a{\}b,c}d)",
R"({a,b{{1,2}e}f)",
R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
}) {
std::cout << string << '\n';
for (auto expansion : expand(string)) {
std::cout << " " << expansion << '\n';
}
std::cout << '\n';
}
return 0;
}</syntaxhighlight>
 
=={{header|C sharp|C#}}==
This approach turns the string into a tree structure, with Tokens that are either text, a concatenation or an alteration.
{{works with|C sharp|8}}
<syntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
Line 1,101 ⟶ 919:
 
{{trans|Python}}
<syntaxhighlight lang="csharp">public static class BraceExpansion
{
const char L = '{', R = '}', S = ',';
Line 1,173 ⟶ 991:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}</pre>
=={{header|C++}}==
C++11 solution:
 
<syntaxhighlight lang="cpp">#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
 
namespace detail {
 
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end)
{ }
template <typename Lambda>
bool next(Lambda istoken)
{
if (_tbegin == _end) {
return false;
}
_tbegin = _tend;
for (; _tend != _end && !istoken(*_tend); ++_tend) {
if (*_tend == '\\' && std::next(_tend) != _end) {
++_tend;
}
}
if (_tend == _tbegin) {
_tend++;
}
return _tbegin != _end;
}
ForwardIterator begin() const { return _tbegin; }
ForwardIterator end() const { return _tend; }
bool operator==(char c) { return *_tbegin == c; }
};
 
template <typename List>
void append_all(List & lista, const List & listb)
{
if (listb.size() == 1) {
for (auto & a : lista) {
a += listb.back();
}
} else {
List tmp;
for (auto & a : lista) {
for (auto & b : listb) {
tmp.push_back(a + b);
}
}
lista = std::move(tmp);
}
}
 
template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{
std::vector<List> alts{ { String() } };
while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {
if (token == '{') {
append_all(alts.back(), expand<String, List>(token));
} else if (token == ',') {
alts.push_back({ String() });
} else if (token == '}') {
if (alts.size() == 1) {
for (auto & a : alts.back()) {
a = '{' + a + '}';
}
return alts.back();
} else {
for (std::size_t i = 1; i < alts.size(); i++) {
alts.front().insert(alts.front().end(),
std::make_move_iterator(std::begin(alts[i])),
std::make_move_iterator(std::end(alts[i])));
}
return std::move(alts.front());
}
} else {
for (auto & a : alts.back()) {
a.append(token.begin(), token.end());
}
}
}
List result{ String{ '{' } };
append_all(result, alts.front());
for (std::size_t i = 1; i < alts.size(); i++) {
for (auto & a : result) {
a += ',';
}
append_all(result, alts[i]);
}
return result;
}
 
} // namespace detail
 
template <
typename ForwardIterator,
typename String = std::basic_string<
typename std::iterator_traits<ForwardIterator>::value_type
>,
typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
detail::tokenizer<ForwardIterator> token(begin, end);
List list{ String() };
while (token.next([](char c) { return c == '{'; })) {
if (token == '{') {
detail::append_all(list, detail::expand<String, List>(token));
} else {
for (auto & a : list) {
a.append(token.begin(), token.end());
}
}
}
return list;
}
 
template <
typename Range,
typename String = std::basic_string<typename Range::value_type>,
typename List = std::vector<String>
>
List expand(const Range & range)
{
using Iterator = typename Range::const_iterator;
return expand<Iterator, String, List>(std::begin(range), std::end(range));
}
 
int main()
{
for (std::string string : {
R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
R"(It{{em,alic}iz,erat}e{d,}, please.)",
R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
R"(a{b{1,2}c)",
R"(a{1,2}b}c)",
R"(a{1,{2},3}b)",
R"(a{b{1,2}c{}})",
R"(more{ darn{ cowbell,},})",
R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
R"({a,{\,b}c)",
R"(a{b,{{c}})",
R"({a{\}b,c}d)",
R"({a,b{{1,2}e}f)",
R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
}) {
std::cout << string << '\n';
for (auto expansion : expand(string)) {
std::cout << " " << expansion << '\n';
}
std::cout << '\n';
}
return 0;
}</syntaxhighlight>
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defstruct alternation
(alternatives nil :type list))
 
Line 1,288 ⟶ 1,281:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|D}}==
{{trans|Python}}
This code is not UTF-corrected, because it uses slicing instead of front, popFront, etc.
<syntaxhighlight 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)
Line 1,444 ⟶ 1,436:
{a,b{2e}f
</pre>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<syntaxhighlight lang="elixir">defmodule Brace_expansion do
def getitem(s), do: getitem(String.codepoints(s), 0, [""])
Line 1,528 ⟶ 1,519:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Go}}==
<code>expand.go</code>:
<syntaxhighlight lang="go">package expand
 
// Expander is anything that can be expanded into a slice of strings.
Line 1,734 ⟶ 1,724:
}</syntaxhighlight>
<code>expand_test.go</code>
<syntaxhighlight lang="go">package expand
 
import (
Line 1,872 ⟶ 1,862:
ok rosetta_code/Brace_expansion 3.347s
</pre>
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">class BraceExpansion {
static void main(String[] args) {
for (String s : [
Line 1,947 ⟶ 1,936:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}</pre>
 
=={{header|Haskell}}==
[http://www.reddit.com/r/readablecode/comments/1w6exe/p6_crosswalk_braceexpansionparses/cf229at "Here is a direct translation to Haskell using parsec"] (of [http://rosettacode.org/mw/index.php?title=Brace_expansion&oldid=175567#Raku an earlier version of the Raku solution]):
 
<syntaxhighlight lang="haskell">import qualified Text.Parsec as P
 
showExpansion :: String -> String
Line 2,017 ⟶ 2,005:
{}} some }{\\ edge \,{ cases, {here} \\\\\}
{}} some }{\\ edge \,{ cases, {here} \\\\\}</pre>
 
=={{header|J}}==
 
Implementation:
 
<syntaxhighlight lang=J"j">
NB. legit { , and } do not follow a legit backslash:
legit=: 1,_1}.4>(3;(_2[\"1".;._2]0 :0);('\';a.);0 _1 0 1)&;:&.(' '&,)
Line 2,068 ⟶ 2,055:
Examples:
 
<syntaxhighlight lang=J"j"> >expand t1
~/Downloads/*.jpg
~/Downloads/*.gif
Line 2,098 ⟶ 2,085:
 
Finally, for each integer that we've used to mark delimiter locations, split out each of the marked options (each with a copy of that group's prefix and suffix). (Then when all that is done, take the absolute values convert back to unicode for the final result.)
 
=={{header|Java}}==
Should be able to handle all printable Unicode.
<syntaxhighlight lang="java">public class BraceExpansion {
 
public static void main(String[] args) {
Line 2,169 ⟶ 2,155:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}</pre>
 
=={{header|JavaScript}}==
 
Line 2,180 ⟶ 2,165:
Each node of the parse tree consists of one of two simple functions (AND: syntagmatic concatenation, OR: flattening of paradigms) with a set of arguments, each of which may be a plain string or an AND or OR subtree. The expansions are derived by evaluating the parse tree as an expression.
 
<syntaxhighlight lang=JavaScript"javascript">(function () {
'use strict'
 
Line 2,406 ⟶ 2,391:
Sample of parse trees logged to the console:
 
<syntaxhighlight lang=JavaScript"javascript">{
"fn": "[function and]",
"args": [
Line 2,441 ⟶ 2,426:
]
}</syntaxhighlight>
=={{header|jq}}==
''Adapted from [[#Wren|Wren]]''
 
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
 
<syntaxhighlight lang=jq>
# Input: a string
# Emit an array of the expansions
def expand:
 
# Emit [ array, string ]
def getItem($depth):
 
def getGroup($depth):
{ out: [], comma: false, s: . }
| until (.s == "" or .return;
(.s | getItem($depth)) as $t
| $t[0] as $g
| .s = $t[1]
| if .s == "" then .return = [[], ""]
else .out += $g
| if .s[0:1] == "}"
then if .comma then .return = [.out, .s[1:]]
else .return = [ (.out | map( "{" + . + "}" )), .s[1:]]
end
else if .s[0:1] == ","
then .comma = true
| .s |= .[1:]
else .
end
end
end)
| if .return then .return else [[], ""] end ;
 
{ out: [""], s: .}
| until( (.s == "") or .return;
.c = .s[0:1]
| if ($depth > 0) and (.c == "," or .c == "}")
then .return = [.out, .s]
else .cont = false
| if .c == "{"
then (.s[1:] | getGroup($depth+1)) as $x
| if $x[0] | length > 0
# conform to the "lexicographic" ordering requirement
then .out |= [ .[] as $o | $o + $x[0][] ]
| .s = $x[1]
| .cont = true
else .
end
else .
end
end
| if (.cont | not)
then if (.c == "\\") and ((.s|length) > 1)
then .c += .s[1:2]
| .s |= .[1:]
else .
end
| .out = [.out[] + .c]
| .s |= .[1:]
else .
end )
| if .return then .return else [.out, .s] end ;
 
getItem(0)[0];
def inputs: [
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"It{{em,alic}iz,erat}e{d,}, please.",
"{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
"{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"
];
 
inputs[]
| "\n",
.,
" " + expand[]
</syntaxhighlight>
{{output}}
<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} \\\\\}
</pre>
 
=={{header|Julia}}==
{{trans|Python}} <syntaxhighlight lang="julia"> function getitem(s, depth=0)
out = [""]
while s != ""
Line 2,528 ⟶ 2,623:
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.1.2
 
object BraceExpansion {
Line 2,605 ⟶ 2,700:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Lua}}==
 
Line 2,612 ⟶ 2,706:
Note that this code isn't very memory efficient.
 
<syntaxhighlight lang=Lua"lua">local function wrapEachItem(items, prefix, suffix)
local itemsWrapped = {}
 
Line 2,721 ⟶ 2,815:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">(*The strategy is to first capture all special sub-expressions and reformat them so they are semantically clear. The built in function Distribute could then do the work of creating the alternatives, but the order wouldn't match that given in the instructions (although as a set the alternatives would be correct). I'll take a more complicated route so as to follow the instructions exactly.*)
 
(*A few named constants for readability.*)
Line 2,788 ⟶ 2,881:
{}} some }{,\\ edge \,{ cases, {here} \\\\\}
{}} some }{,\\ edge \,{ cases, {here} \\\\\}</pre>
 
=={{header|Nim}}==
{{trans|Seed7}}
<syntaxhighlight lang=Nim"nim">proc expandBraces(str: string) =
 
var
Line 2,867 ⟶ 2,959:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}</pre>
 
=={{header|Perl}}==
 
Line 2,875 ⟶ 2,966:
So here is a manual solution that implements the specification precisely:
 
<syntaxhighlight lang="perl">sub brace_expand {
my $input = shift;
my @stack = ([my $current = ['']]);
Line 2,918 ⟶ 3,009:
 
Usage demonstration:
<syntaxhighlight lang="perl">while (my $input = <DATA>) {
chomp($input);
print "$input\n";
Line 2,959 ⟶ 3,050:
 
</pre>
 
=={{header|Phix}}==
Fairly straightforward recursive solution
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Brace_expansion.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 3,057 ⟶ 3,147:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|PHP}}==
{{trans|Python}}
<syntaxhighlight lang="php">function getitem($s,$depth=0) {
$out = [''];
while ($s) {
Line 3,162 ⟶ 3,251:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de braceExpand (Str)
(let Lst
(make
Line 3,197 ⟶ 3,285:
(list (car Lst)) ) ) ) ) ) ) )</syntaxhighlight>
Test:
<syntaxhighlight lang=PicoLisp"picolisp">(test
(quote
"~/Downloads/*.jpg"
Line 3,230 ⟶ 3,318:
"{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}" )
(braceExpand "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}") )</syntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang=PowerShell"powershell">
function Expand-Braces ( [string]$String )
{
Line 3,290 ⟶ 3,377:
}
</syntaxhighlight>
<syntaxhighlight lang=PowerShell"powershell">
$TestStrings = @(
'It{{em,alic}iz,erat}e{d,}, please.'
Line 3,338 ⟶ 3,425:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Prolog}}==
<syntaxhighlight lang=Prolog"prolog">
sym(',', commalist) --> ['\\',','], !.
sym(H, Context) --> [H], { not(H = '{'; H = '}'), (Context = commalist -> not(H = ','); true) }.
Line 3,365 ⟶ 3,451:
 
Testing:
<syntaxhighlight lang=Prolog"prolog">
?- brace_expansion("~/{Downloads,Pictures}/*.{jpg,gif,png}", Out).
Out = ["~/Downloads/*.jpg","~/Downloads/*.gif","~/Downloads/*.png","~/Pictures/*.jpg","~/Pictures/*.gif","~/Pictures/*.png"].
Line 3,376 ⟶ 3,462:
 
</syntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang="python">def getitem(s, depth=0):
out = [""]
while s:
Line 3,448 ⟶ 3,533:
 
</pre>
 
=={{header|Racket}}==
{{trans|Python}}
<syntaxhighlight lang="racket">#lang racket/base
(require racket/match)
(define (merge-lists as . bss)
Line 3,524 ⟶ 3,608:
{}} some }{,{\\ edge ,}{ cases, {here} \\\\}
{}} some }{,{\\ edge ,}{ cases, {here} \\\\}</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 3,532 ⟶ 3,615:
 
On the other end, we recursively walk the parse tree returning expanded sublists, and we do the cartesian concatenation of sublists at each level by use of the <tt>X~</tt> operator, which is a "cross" metaoperator used on a simple <tt>~</tt> concatenation. As a list infix operator, <tt>X~</tt> does not care how many items are on either side, which is just what you want in this case, since some of the arguments are strings and some are lists. Here we use a fold or reduction form in square brackets to interpose the cross-concat between each value generated by the map, which returns a mixture of lists and literal strings. One other thing that might not be obvious: if we bind to the match variable, <tt>$/</tt>, we automatically get all the syntactic sugar for its submatches. In this case, <tt>$0</tt> is short for <tt>$/[0]</tt>, and represents all the submatches captured by 0th set of parens in either <tt>TOP</tt> or <tt>alt</tt>. <tt>$&lt;meta&gt;</tt> is likewise short for <tt>$/&lt;meta&gt;</tt>, and retrieves what was captured by that named submatch.
<syntaxhighlight lang="raku" line>grammar BraceExpansion {
token TOP { ( <meta> | . )* }
token meta { '{' <alts> '}' | \\ . }
Line 3,637 ⟶ 3,720:
{a\}bd
{acd</pre>
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*- REXX --------------------------------------------------------------
* Brace expansion
* 26.07.2016
Line 3,893 ⟶ 3,975:
{}
1 {}</pre>
 
=={{header|Ruby}}==
{{trans|Python}}
<syntaxhighlight lang="ruby">def getitem(s, depth=0)
out = [""]
until s.empty?
Line 3,966 ⟶ 4,047:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">const OPEN_CHAR: char = '{';
const CLOSE_CHAR: char = '}';
const SEPARATOR: char = ',';
Line 4,186 ⟶ 4,266:
 
{{trans|Python}}
<syntaxhighlight lang="rust">
fn main() {
let input = "~/{Downloads,Pictures}/*.{jpg,gif,png}
Line 4,294 ⟶ 4,374:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Scala}}==
{{works with|Scala|2.11}}
<syntaxhighlight lang="scala">
import collection.mutable.ListBuffer
case class State(isChild: Boolean, alts: ListBuffer[String], rem: List[Char])
Line 4,330 ⟶ 4,409:
</syntaxhighlight>
Demonstrating:
<syntaxhighlight lang="scala">
println(expand("""~/{Downloads,Pictures}/*.{jpg,gif,png}""") mkString "\n")
println(expand("It{{em,alic}iz,erat}e{d,}, please.") mkString "\n")
Line 4,357 ⟶ 4,436:
{}} some }{,\\ edge \,{ cases, {here} \\\\\}
</pre>
 
=={{header|Scheme}}==
<syntaxhighlight lang=Scheme"scheme">
(define (parse-brackets str)
;; We parse the bracketed strings using an accumulator and a stack
Line 4,451 ⟶ 4,529:
;; '("Ited" "Ite" "Itemed" "Iteme" "Italiced" "Italice" "Itized" "Itize" "Iterated" "Iterate")
</syntaxhighlight>
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: expandBraces (in string: stri) is func
Line 4,539 ⟶ 4,616:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">func brace_expand (input) {
var current = ['']
var stack = [[current]]
Line 4,632 ⟶ 4,708:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Simula}}==
{{trans|Python}}
<syntaxhighlight lang="simula">CLASS ARRAYLISTS;
BEGIN
 
Line 4,721 ⟶ 4,796:
END;
 
END;</syntaxhighlight><syntaxhighlight lang="simula">EXTERNAL CLASS ARRAYLISTS;
ARRAYLISTS
BEGIN
Line 4,900 ⟶ 4,975:
 
</pre>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
templates braceExpansion
composer braceParse
Line 4,915 ⟶ 4,989:
 
templates collateSequence
data part <[]|''> local
@: [''];
$... -> #
$@!
when <´part´ '.*'> do
def part: $;
@: [$@... -> '$;$part;'];
Line 4,968 ⟶ 5,043:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<syntaxhighlight lang="tcl">package require Tcl 8.6
 
proc combine {cases1 cases2 {insert ""}} {
Line 5,039 ⟶ 5,114:
}</syntaxhighlight>
Demonstrating:
<syntaxhighlight lang="tcl">foreach testcase {
"~/{Downloads,Pictures}/*.{jpg,gif,png}"
"It{{em,alic}iz,erat}e{d,}, please."
Line 5,071 ⟶ 5,146:
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
=={{header|TXR}}==
 
The approach here is to parse the notation into a nested tree of strings. In the following diagram the <code>-></code> arrow indicates that the tree on the left denotes the list of output strings on the right.
 
A list with no operator symbol denotes catenation:
 
<pre>("foo" "bar") -> ("foobar")</pre>
 
The <code>/</code> symbol (slash, usually denoting arithmetic division) denotes alternation:
 
<pre>(/ "foo" "bar") -> ("foo" "bar")
("inter" (/ "pol" "pret") "ation") -> ("interpolation" "interpretation")</pre>
 
This notation is processed by the <code>bexp-expand</code> function to produce the list of strings which it denotes. The <code>bexp-parse</code> function parses a string containing brace expansion into the above notation.
 
The backslashes and edge cases are handled between the tokenizing and parsing. Backslashed characters are represented as tokens which include the backslash. Thus the <code>\{</code> token compares unequal to <code>{</code> and isn't mistaken for it. These backslashed tokens just look like any other text that has no special meaning.
 
The empty <code>{}</code> is handled as a token, but other cases of braces containing no commas are handled in the parser.
 
When the parser has scanned a complete, valid brace that contains no comma, instead of generating a <code>(/ ...)</code> tree node from the content, it generates <code>("{" ... "}")</code>, rendering the braces as literal strings. The <code>...</code> content may contain <code>/</code> operators, as required.
 
When the parser has scanned an incomplete brace, it puts out <code>("{" ...)</code>: the dangling brace is represented literally, followed by the items that have been parsed out. The comma elements are preserved in this case; the lack of a closing brace turns off their meaning.
 
In the main case of a balanced brace with commas, the parsed out elements are split on the commas, which are removed, and that forms the arguments of <code>/</code> node.
 
<syntaxhighlight lang="txrlisp">;; API
(defun brace-expand (str)
(bexp-expand (bexp-parse str)))
 
;; parser
(defstruct bexp-parse-ctx ()
str
toks)
 
(defun bexp-parse (str)
(let ((ctx (new bexp-parse-ctx
str str
;; tokenizer
toks (remqual "" (tok #/([{},]|{}|\\\\|\\.)/ t str)))))
(build
(whilet ((next (pop ctx.toks)))
(add
(if (equal next "{")
(bexp-parse-brace ctx)
next))))))
 
(defun bexp-parse-brace (ctx)
(buildn
(let ((orig-toks ctx.toks))
(caseq (whilet ((next (pop ctx.toks)))
(casequal next
("{" (add (bexp-parse-brace ctx)))
("}" (return :ok))
(t (add next))))
(:ok
(cond
((memqual "," (get))
(flow (get)
(split* @1 (op where (op equal ",")))
(cons '/)))
(t
(add* "{")
(add "}")
(get))))
(nil
(add* "{")
(get))))))
 
;; expander
(defun bexp-expand (tree : (path (new list-builder)))
(build
(match-case tree
(() (add (cat-str path.(get))))
(((/ . @alt) . @rest)
(let ((saved-path path.(get)))
(each ((elem alt))
path.(oust saved-path)
(pend (bexp-expand (cons elem rest) path)))))
((@(consp @succ) . @rest)
(pend (bexp-expand (append succ rest) path)))
((@head . @rest)
path.(add head)
(pend (bexp-expand rest path))))))
 
;; Tests
(tprint (brace-expand "~/{Downloads,Pictures}/*.{jpg,gif,png}"))
(tprint (brace-expand "It{{em,alic}iz,erat}e{d,}, please."))
(tprint (brace-expand "{,{,gotta have{ ,\\, again\\, }}more }cowbell!"))
(tprint (brace-expand "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"))</syntaxhighlight>
 
{{out}}
 
<pre>~/Downloads/*.jpg
~/Downloads/*.gif
~/Downloads/*.png
~/Pictures/*.jpg
~/Pictures/*.gif
~/Pictures/*.png
Itemized, please.
Itemize, please.
Italicized, please.
Italicize, please.
Iterated, please.
Iterate, please.
cowbell!
more cowbell!
gotta have more cowbell!
gotta have\, again\, more cowbell!
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
{}} some }{,{\\ edge \,}{ cases, {here} \\\\\}
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|Python}}
<syntaxhighlight lang="vbnet">Module Module1
 
Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)
Line 5,176 ⟶ 5,362:
=={{header|Wren}}==
{{trans|Python}}
<syntaxhighlight lang=ecmascript"wren">var getGroup // forward declaration
 
var getItem = Fn.new { |s, depth|
Line 5,274 ⟶ 5,460:
=={{header|zkl}}==
This is a two pass algorithm (2*length(string)), one pass to find valid {} pairs, the next pass to expand them.
<syntaxhighlight lang="zkl">fcn eyeball(code,ps=L(),brace=False){ //-->indexes of valid braces & commas
cs:=L();
foreach c in (code){ // start fresh or continue (if recursing)
Line 5,306 ⟶ 5,492:
strings
}</syntaxhighlight>
<syntaxhighlight lang="zkl">foreach bs in (T("It{{em,alic}iz,erat}e{d,}", "~/{Downloads,Pictures}/*.{jpg,gif,png}",
"It{{em,alic}iz,erat}e{d,}, please.", "a{2,1}b{X,Y,X}c", 0'|a\\{\\\{b,c\,d}|,
"{a,b{c{,{d}}e}f", 0'|{,{,gotta have{ ,\, again\, }}more }cowbell!|,
9,476

edits