In message "Re: [ruby-core:26282] New Enumerable#flat_map"
    on Sun, 25 Oct 2009 05:02:28 +0900, Marc-Andre Lafortune <ruby-core-mailing-list / marc-andre.ca> writes:
|
|Hi Matz,
|
|I noticed the new Enumerable#flat_map (aka collect_concat) and I was
|wondering what prompted the creation of this method.

It's taken from flatMap from Scala or concatMap from Haskell.

|In what kind of circumstances is flat_map needed?

The following is the direct translation from the example in the
"Programming Scala" book:

  class Person
    def initialize(name, is_male, *children)
      @name = name
      @is_male = is_male
      @children = children
    end
    attr_reader :name, :children
    def male?
      !! @is_male
    end
  end

  alice = Person.new("Alice", false)
  bob = Person.new("Bob", true)
  chris = Person.new("Chris", false, alice, bob)

  p [alice, bob, chris].reject(&:male?)
    .flat_map{|p| p.children.map{|c| [p.name,c.name]}}

which prints name pairs of a mother and a child.

|I'm probably missing something, but what is the difference between:
|    enum.collect_concat(&block)
|and
|    enum.map(&block).flatten(1)
|?

They do same thing, besides flat_map is shorter, clearer, and bit more
efficient, without any magic number.  I should have made the default
value for #flatten to 1, but it's different story.

							matz.