Comma quibbling: Difference between revisions

m
→‎{{header|PHP}}: fix formatting.
m (→‎{{header|dc}}: Better register names and comments.)
m (→‎{{header|PHP}}: fix formatting.)
 
(4 intermediate revisions by the same user not shown)
Line 1,475:
 
[(p)rint: get next item from stack in r register and print it. If there are
more than 2 items left, printon athe commaregister stack (c) and recurse.which Ifnever theredrops arebelow exactlyone
two items leftitem), print "a and "comma (ac) and returnrecurse.]sx 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
 
Line 3,424 ⟶ 3,425:
<syntaxhighlight lang="php"><?php
 
function quibble($arr) {
 
$words = switch (count($arr);) {
 
case 0:
if($words == 0){
return '{}';
 
}elseif($words == 1){
case 1:
return '"{{'.$arr[0].'}'}";
}elseif($words == 2){
 
return '{'.$arr[0].' and '.$arr[1].'}';
default:
}else{
return '{'. $left = implode(', ', array_splicearray_slice($arr, 0, -1) ). ' and '.$arr[0].'}';
$right = array_slice($arr, -1)[0];
}
return '"{{'.$arr[0].'left} and '.{$arr[1].'right}}'";
 
}
 
}
Line 3,450 ⟶ 3,454:
foreach ($tests as $test) {
echo quibble($test) . PHP_EOL;
}</syntaxhighlight>
?></syntaxhighlight>
{{out}}
<pre>{}
Line 4,546 ⟶ 4,551:
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{trans|AWK}}
{{works with|Korn Shell}}
<syntaxhighlight lang="bash">quibble() {
{{works with|Z Shell}}
# Here awk(1) is easier than sed(1).
<syntaxhighlight lang="bash">
awk 'BEGIN {
quibble() {
for (i = 1; i < ARGC - 2; i++) s = s ARGV[i] ", "
printf '{'
i = ARGC - 2; if (i > 0) s = s ARGV[i] " and "
i = ARGC - 1; ifwhile (i( $# > 0)2 s = s)); ARGV[i]do
printf "{'%s}\n", s' "$1"
shift
exit 0
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="bashzsh">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
1,480

edits