24
3
What are some clever (brief and idiomatic) approaches to taking a list of strings and returning a single properly punctuated string built from the list, with each element quoted.
This came up for me while experimenting with Groovy, for which my too-literal, but illustrative solution is
def temp = things.collect({"\'${it}\'"})
switch (things.size()) {
case 1:
result = temp[0]
break
case 2:
result = temp.join(" and ")
break
default:
result = temp.take(temp.size()-1).join(", ") + ", and " + temp[-1]
break
}
That is, ['1']
should yield '1'
, ['1','2']
should yield '1 and 2'
, [see what I did there?] and ['1','2','3']
should yield '1, 2, and 3'
.
I have some good answers for Groovy, but I'd like to see what other languages can do.
What are some compact clever approaches in various languages that take advantage of the features and idioms of those languages?
Input is an Array of characters or a single string. i.e.
['1','2']
or"['1', '2']"
– Optimizer – 2014-09-11T18:56:01.9706Welcome to PPCG. Generally questions posted here are challenges to the community. As such they need an objective winning criteria. I believe this question maps reasonably well to being a [tag:code-golf] challenge. Can you tag it as such? If so, I think you should tighten up the input and output specifications a bit. – Digital Trauma – 2014-09-11T18:58:35.377
@DigitalTrauma: Good suggestion. Thanks. I'd like it to focus on producing the most idiomatic code; that is, the code that takes best advantage of the capabilities of the language. Is that a fair challenge (and of so, how should I tag it)? – orome – 2014-09-11T19:02:30.900
@Optimizer: An array of characters (of of strings). – orome – 2014-09-11T19:05:14.247
@MartinBüttner: For here, I'll go with length ([tag:code-golf]) then. – orome – 2014-09-11T19:21:58.717
7
This would be more interesting with real sentences:
– ThisSuitIsBlackNot – 2014-09-11T21:06:05.757['we invited the stripper','JFK','Stalin']
1Can we assume that the strings themselves don't contain commas already? – Martin Ender – 2014-09-11T21:16:04.810
@MartinBüttner: Good question. Assume not: no commas or "and"s to mess things up. – orome – 2014-09-11T21:20:56.587
Do we need to make it a complete CLI-executable solution? Must it be wrapped in a function declaration, or just the relevant code with setup instructions? Is the setup included in the scoring size? – Adrian – 2014-09-12T06:15:08.773
2
Challenge should have been titled "Who gives a ---- about an Oxford comma?"
– Igby Largeman – 2014-09-12T07:14:25.263My old English teacher would be horrified to see a comma before an "and". The last result should read
'1, 2 and 3'
to be proper English English rather than the Americanised rubbish spoken in the colonies. :) – OldCurmudgeon – 2014-09-18T10:19:46.3733@OldCurmudgeon I think you mean "Americanized rubbish" ;) – ThisSuitIsBlackNot – 2014-09-21T18:59:06.763