Following the educational tradition of:
I chose this particular problem purely by chance after being surprised that solving it in Perl turned out to be more awkward than I'd expected. Curious as to whether this awkwardness was specific to Perl, I then tried solving it in Ruby, Python and Haskell. Hence this node. :-)
Given an input string, for example "ZBBBCZZ", produce a list, for example, ["Z", "BBB", "C", "ZZ"].
That is, break the input string into pieces based on change of character.
My preferred solutions in Perl, Ruby, Python and Haskell follow. Improvements welcome.
This was discussed at length on the Ruby-Talk mailing list, with many different solutions offered. My favourite is similar to tye's Perl solution:
This problem was also discussed on Python-list. My favourite uses Python's SML-inspired itertools library:
Browsing the Haskell Data.List documentation, I noticed that a Haskell solution seems trivial courtesy of Data.List's group/groupBy function:
As you might expect, the only solution that I found truly satisfying was the Haskell one :-) ... though this seems to be more of a library issue than a language one.
BTW, does anyone know of a CPAN module that can solve this problem directly? I took a quick look at:
I'm also curious to learn about plans for Perl 6 "functional-style" libraries. I've been impressed by Haskell's libraries and hope they will help inspire some of the new Perl 6 library.
Anyway, I'd find it interesting and educational to compare solutions to this little problem in a variety of other languages. So, please respond away in your favourite language!
2-sep-2007: Updated references with some more links based on the responses below.