http://www.perlmonks.org?node_id=632023

Following the educational tradition of:

this meditation describes an arbitrary problem to be solved in as many different languages as possible.

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. :-)

The Problem

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.

Perl

My favourite solution from Split a string based on change of character was given in the first response by tye:

my $s = "ZBBBCZZ"; my @x; push @x, $1 while $s =~ /((.)\2*)/g;

Ruby

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:

s = "ZBBBCZZ" x = [] s.scan(/((.)\2*)/){x.push [$~[0]]}

Python

This problem was also discussed on Python-list. My favourite uses Python's SML-inspired itertools library:

import itertools s = "ZBBBCCZZ" x = [''.join(g) for k, g in itertools.groupby(s)]

Haskell

Browsing the Haskell Data.List documentation, I noticed that a Haskell solution seems trivial courtesy of Data.List's group/groupBy function:

group "ZBBBCCZZ"

Discussion

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:

but didn't notice any obvious, trivial way to do it with those libraries.

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!

References

2-sep-2007: Updated references with some more links based on the responses below.