ruby picture

RCR 242: Add collect_flatten and collect_flatten! to Array

Submitted by NickJohnson (Sun Apr 11 16:04:40 UTC 2004)

Abstract

A new method of class array, tentatively named collect_flatten and collect_flatten! would ease certain programming constructs, especially in mathematics.

Problem

Although Array's collect method is very useful, it falls short for blocks which would like to add more than one element to the resultant array.

For example, suppose I want to construct the Koch curve (see I would start by creating a class for a line segment in R^2 space. Then, with the current implementation of Array, I would create an array containing one such line segment, and call:

setOfLineSegments=[LineSegment.new(...)] setOfLineSegments.collect! do |ls|

     [
         # each line segment is
         # replaced by 4
         LineSegment.new(...)
         LineSegment.new(...)
         LineSegment.new(...)
         LineSegment.new(...)
     ]
end setOfLineSegments.flatten!

Such iterative approximation of an infinite and recursively defined set is common. Such code would be more readable with collect_flatten and collect_flatten! methods of array.

Proposal

I propose that two methods be added to class Array: collect_flatten and collect_flatten!, which each combine the effects of collect and flatten.

Analysis

This would cause no incompatibilities with previous versions of Ruby.

These methods could be implemented as either a call to collect and then to flatten, or as a call to collect and concat (either would be ok with me).

I feel that the collect and flatten pair makes more intuitive sense, though the collect and concat pair may be faster.

Implementation

class Array

def collect_flatten(&block)

     r = collect(&block)
     r.flatten     
end

def collect_flatten!(&block)

     collect!(&block)
     flatten!
end

end

ruby picture
Comments Current voting

Have you considered inject, like this?

segments = [1, 2, 3]
segments = segments.inject([]) do |result, seg|
  # compute new segments
  result + [seg, seg, seg]
end
p segments  # [1, 1, 1, 2, 2, 2, 3, 3, 3]

-- Simon Strandgaard


Strongly opposed 3
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .