Tuesday, March 15, 2011

How to write a delimited list in Magik

Over the years I have seen lots of approaches to writing a delimited string. They usually involved creating a loop, writing a delimiter after each element in the collection and then finally removing the last delimiter that was added in the loop.

For example, if you have a list of voltages and you want to concatenate them all in a string that is delimited with a comma and a space ", " you could write something like this...

voltage_string << "  "
_for i_volt _over voltages.fast_elements()
_loop
voltage_string +<< i_volt+", "
_finally
voltage_string << voltage_string.subseq(1,voltage_string.size-2)+"."
_endloop


... or you could use the core write_string_with_separator() procedure and write equivalent code like this...

voltage_string << write("  ",
write_string_with_separator(voltages,", "),
".")


I like the latter approach because it is more concise and it very clearly indicates what you are trying to do... write a string with delimiter.

No comments: