the gauntlet is caught

further to this stuff, a ruby version:

class Array
  def group_seq
    reduce([]) do |acc, obj|
      if acc != [] && (yield obj) == (yield acc.last.first)
        acc.last << obj         
        acc                     
      else              
        acc << [obj]            
      end               
    end         
  end   
end

The (yield obj) == (yield acc.last.first) will mean that things get grouped according to the value of the predicate. If you change the == to &&, then only values for which the predicate is true will be grouped.

It turns out that python already has this in it’s standard library, so that’s easy:

map(lambda (b,i): list(i), groupby([1,2,3,4,5,6,7,8], lambda n: n % 2 == 0))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s