Given a seq[string] txts I have the following code:
let withBullets = collect(newSeq):
for s in txts: &"* {s}"
dialog "Here is what happened:\n" & withBullets.join("\n") & "\nDo you understand?"
In Python I could write:
dialog "Here is what happened:\n" + "\n".join([ f"* {t}" for s in txts]) + "\nDo you understand?"
Is there a way in Nim to do this as a one-liner as well or at least to write it without the intermediate variable withBullets?
PS: I am giving the Python example not proposing it is "better" than Nim (I totally dislike Python's join function belonging to the list separator string and not to the list!), but I do think Python's inline comprehension can be rather concise.
When posting code it's really helpful if it runs on the playground, makes it easier to tests solutions :) Here are a couple of options for one-liners:
import sugar, strformat, strutils
var txts = @["Hello", "world", "hows", "life"]
let withBullets = collect(newSeq):
for s in txts: &"* {s}"
echo "Here is what happened:\n" & withBullets.join("\n") & "\nDo you understand?"
import sequtils
echo "Here is what happened:\n" & txts.mapIt(&"* {it}").join("\n") & "\nDo you understand?"
echo "Here is what happened:\n* " & txts.foldl(&"{a}\n* {b}") & "\nDo you understand?"
Sorry about my sloppy snippet. I agree: Runnable code is here friendlier whenever possible. Thanks for pointing it out (and not just grumbling about it behind the scene).
And of course, super thanks for your solutions! The last one (... (collect(..., for ...).join ...) was the one I had tried to achieve myself, but I didn't think of writing the for code block as argument to the collect template.
one more solution that only works on devel, showing off collect without the initial newSeq and nested strformatting: this could also be one line but it'd get pretty messy with quote-escapes;
echo &"""Here is what happened:
{collect(for s in txts: &"* {s\}").join("\n")}
Do you understand?"""