From: Marc-Andre Lafortune Date: 2009-10-26T20:03:54+09:00 Subject: [ruby-core:26317] Re: New Enumerable#flat_map Thanks to both of you for the answers :-) I've written some basic Rubyspecs for it. On Sun, Oct 25, 2009 at 6:48 PM, Yukihiro Matsumoto wrote: > > In message "Re: [ruby-core:26282] New Enumerable#flat_map" > � �on Sun, 25 Oct 2009 05:02:28 +0900, Marc-Andre Lafortune 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. > >