Enumerable.partition

Hi –

I see that Enumerable.partition has been added somewhere between 1.6.7
and 1.7.3. It’s implemention is equivilent to

module Enumerable
def partition
result = [[], [[]]
each do |value|
result[yield(value) ? 0 : 1].push(value)
end
result
end
end

e.g. [0, 1, 2, 3].new_parition { |x| x > 1 }
gives [[2, 3], [0, 1]]

Please (pretty please) can this be changed to the much more powerful:

module Enumerable
def new_partition(default = nil)
result = Hash.new(default)
each do |value|
key = yield(value)
if result.has_key?(key)
result[key].push(value)
else
result[key] = [value]
end
end
result
end
end

e.g. [0, 1, 2, 3].new_partition { |x| x > 1 }
gives {false=>[0, 1], true=>[2, 3]}

Hopefully this won’t break too much code in 1.7.3. It’s very useful:

[-2, -1, 0, 1, 2].new_partition { |x| x <=> 0 }

=> {0=>[0], 1=>[1, 2], -1=>[-2, -1]}

The ability to override the hash default is helpful:

a = [0, 1, 2]
h = a.partition([]) { |x| x <=> 0 }

=> {0=>[0], 1=>[1, 2]}

puts(“there are #{h[-1].size} negative numbers in a”)

Thanks,

Tom

Hi,

Please (pretty please) can this be changed to the much more powerful:

module Enumerable
def new_partition(default = nil)
result = Hash.new(default)
each do |value|
key = yield(value)
if result.has_key?(key)
result[key].push(value)
else
result[key] = [value]
end
end
result
end
end

e.g. [0, 1, 2, 3].new_partition { |x| x > 1 }
gives {false=>[0, 1], true=>[2, 3]}

This seems nice.

Hopefully this won’t break too much code in 1.7.3. It’s very useful:

What about new name, “classify” or something else?

···

At Fri, 18 Oct 2002 00:27:23 +0900, Tom Payne wrote:


Nobu Nakada

nobu.nokada@softhome.net wrote in message news:200210180020.g9I0KVo14331@sharui.nakada.kanuma.tochigi.jp

What about new name, “classify” or something else?

Fair enough, but there’s no need to include both “partition” and
“new_parition/classify”. new_partition does all partition does and
more.

Tom

Mon, 21 Oct 2002 09:32:16 +0900, Tom Payne google@tompayne.org pisze:

Fair enough, but there’s no need to include both “partition” and
“new_parition/classify”. new_partition does all partition does
and more.

partition is easier to use in the case it’s appropriate:
s1, s2 = s.partition {|x| …}

Haskell and SML have such partition.

···


__("< Marcin Kowalczyk
__/ qrczak@knm.org.pl
^^ http://qrnik.knm.org.pl/~qrczak/

Hi,

···

In message “Re: Enumerable.partition” on 02/10/21, Tom Payne google@tompayne.org writes:

What about new name, “classify” or something else?

Fair enough, but there’s no need to include both “partition” and
“new_parition/classify”. new_partition does all partition does and
more.

But still, I feel they are different. The original one does split
elements based on boolean value, whereas the new one associates
evaluated values and corresponding elements.

						matz.