A common programming problem without a generic solution?

In no language in which I have worked is it trivial to handle special cases for the last item in a loop (as far as I know!). For instance, we want to loop putting a comma between each item in a list... until the last one, when we want a period.

Of course, we solve these problems all the time. But in my experience, we solve them ad hoc.

3 comments:

Python and Scala, among many, provide a case-specific solution for strings in the form of the `join` and `mkString` methods, respectively.

In general, you are right: languages and standard libraries don't provide a way to special-case the last element in a generic collection when looping. Languages with pattern matching do provide a fairly minimal syntax for doing so, but you have to use recursion instead of looping. Even then, in those contexts using direct recursion is often frowned upon in favor of higher-order functions such as `fold`.

Out of curiosity: do you have a case for doing this other than making a delimited string?