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 – 11 years ago6Welcome 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 – 11 years ago
@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 – 11 years ago
@Optimizer: An array of characters (of of strings). – orome – 11 years ago
@MartinBüttner: For here, I'll go with length ([tag:code-golf]) then. – orome – 11 years ago
7
This would be more interesting with real sentences:
– ThisSuitIsBlackNot – 11 years ago['we invited the stripper','JFK','Stalin']1Can we assume that the strings themselves don't contain commas already? – Martin Ender – 11 years ago
@MartinBüttner: Good question. Assume not: no commas or "and"s to mess things up. – orome – 11 years ago
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 – 11 years ago
2
Challenge should have been titled "Who gives a ---- about an Oxford comma?"
– Igby Largeman – 11 years agoMy 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 – 11 years ago3@OldCurmudgeon I think you mean "Americanized rubbish" ;) – ThisSuitIsBlackNot – 11 years ago