Comma quibbling: Difference between revisions
m
→{{header|PHP}}: fix formatting.
(→{{header|Commodore BASIC}}: Add implementation) |
m (→{{header|PHP}}: fix formatting.) |
||
(6 intermediate revisions by the same user not shown) | |||
Line 1,457:
{{out}}
<pre>["{}", "{ABC}", "{ABC and DEF}", "{ABC, DEF, G and H}"]</pre>
=={{header|dc}}==
<syntaxhighlight lang="dc">[(q)uibble: main entry point. print brackets, calling n in between if stack not
empty.]sx
[ [{]n z 0 !=n [}]pR ]sq
[(n)onempty: if more than 1 item, call m. then print top of stack.]sx
[ z 1 !=m n ]sn
[(m)ore: call f to flip stack into r register, call p to print most of it,
then pop the last item back onto the main stack so it's there to be printed
after we return]sx
[ lfx lpx Lr ]sm
[(f)lip: utility routine to reverse the stack into the r register]sx
[ Sr z 0 !=f ]sf
[(p)rint: get next item from stack in r register and print it. If there are
more than 2 items left on the register stack (which never drops below one
item), print a comma (c) and recurse. If there are exactly two items left,
print " and " (a) and return.]sx
[ Lr n 2 yr >c 2 yr =a 2 yr >p]sp
[(c)omma: utility routine to print a comma followed by a space]sx
[ [, ]n ]sc
[(a)and: utility routine to print " and "]sx
[ [ and ]n ]sa
[run tests]sx
lqx
[ABC] lqx
[ABC] [DEF] lqx
[ABC] [DEF] [G] [H] lqx</syntaxhighlight>
{{out}}
<pre>{}
{ABC}
{ABC and DEF}
{ABC, DEF, G and H}</pre>
=={{header|DCL}}==
Line 1,501 ⟶ 1,541:
{ABC and DEF}
{ABC, DEF, G and H}</pre>
=={{header|Delphi}}==
See [[#Pascal|Pascal]].
Line 3,384 ⟶ 3,425:
<syntaxhighlight lang="php"><?php
function quibble($arr) {
case 0:
return '{}';
case 1:
return "{{$arr[0]}}";
default:
$right = array_slice($arr, -1)[0];
return "{{$left} and {$right}}";
}
}
Line 3,410 ⟶ 3,454:
foreach ($tests as $test) {
echo quibble($test) . PHP_EOL;
}
?></syntaxhighlight>
{{out}}
<pre>{}
Line 4,506 ⟶ 4,551:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
<syntaxhighlight lang="bash">
quibble() {
printf '{'
shift
done
if (( $# )); then
printf '%s' "$1"
shift
fi
if (( $# )); then
printf ' and %s' "$1"
fi
printf '%s\n' '}'
}</syntaxhighlight>
With a slight modification, it will work in any POSIX shell, or even older Bourne-compatible shells as long as they have functions and <b>printf</b>:
<syntaxhighlight lang="sh">
quibble() {
printf '{'
while [ $# -gt 2 ]; do
printf '%s, ' "$1"
shift
done
if [ $# -gt 0 ]; then
printf '%s' "$1"
shift
fi
if [ $# -gt 0 ]; then
printf ' and %s' "$1"
fi
printf '%s\n' '}'
}</syntaxhighlight>
Going the other way, Zsh-specific code can be more compact:
{{works with|Z Shell}}
<syntaxhighlight lang="zsh">quibble() {
printf '{'
if (( $# > 1 )) printf '%s and ' ${(j:, :)@[1,-2]}
printf '%s}\n' $@[-1]
}</syntaxhighlight>
The test code is the same either way:
<syntaxhighlight lang="sh">
quibble
quibble ABC
|