Thursday, March 03, 2016

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.


  1. 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?

  2. Algebraic types in functional programming, eg Haskell. But that's a niche market.

  3. In environments with higher-order functions there will usually be a function for this case. In Scala, for example:

    names.reduceLeft[String] { (acc, n) => acc + ", " + n }

    I lifted the example from 'Scala Collections for the Easily Bored' as I haven't done Scala in a while.


On my tour of Hell...

I saw a man being continually beaten with a carpenter's hammer, blow after merciless blow. "How can this be just?" I asked ...