because Hindley-Milner rocks
Originally I thought I’d entitle this post “Eloquently Not” to highlight how a seemingly eloquent solution could be so utterly poor in light of another solution or a change in circumstances. Sometimes I have to remind myself that small, simple solutions aren’t always the best solution. Sometimes, increasing flexibility at the small expense of enlarging the code base is a necessary trade-off. And sometimes, eloquent is not efficient.
We’ve been dealing with mappings of 2D arrays to 1D in one group because of a disconnect in understanding how data would be held in a library. I thought I’d come up with a very concise means to replace a double for loop used in single traversal (in 2.6 it could be even shorter using chain.from_iterable):
partial_apply = imap( iter, values ) values_iterator = chain( *partial_apply )
This approach performed the traversal faster than the previous approach. It created only what it needed and only when it needed it. It seemed to waste nothing. And yet, when asked to include the ability to iterate over a subset of the array, it failed. It is so rigid a solution that it only works for an entire array!
On a different note, someone asked a rather straightforward question on SO (check if a string contains a range of numbers) to which I gave what I thought was a rather straight forward answer. My answer assumed that there would be only a single number embedded within the string. It also did not provide the validation logic:
val.erase( remove_if( val.begin(), val.end(), ptr_fun( isalpha ) ) );
A single line solution, it suffers from two inefficiencies. The first is that it requires a copy of the original string, else it induces a side-effect. The second is that in the worst case it requires two passes over every element. Juxtaposed to the answer I voted up, a single pass non-destructive approach, it clearly loses out. My hats off to the author, it’s a very clever use of std::locale.