7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mapしてflattenしたらflat_mapになる、をrubyでやってみた

Last updated at Posted at 2015-04-02

@mikamix が mapしてflattenしたらflat_mapじゃと言っていたのでやってみたら確かにそうだった。

def flat_map(arr)
  arr.map{|el| yield el}.flatten
end

def fn(v)
  [v, v]
end

arr = [1,2,3]

p flat_map(arr, &method(:fn)) == arr.flat_map(&method(:fn)) #true

【追記】
@pasela さんからご指摘頂いて上記だと以下の様なケースでEnumerable#flat_mapと同等にならないというチョンボ発覚。

ということで、ご指摘頂いた内容まんまですが

arr = [[1], [2], [3]]

p flat_map(arr, &method(:fn)) == arr.flat_map(&method(:fn)) #=> false

p flat_map(arr, &method(:fn)) #=> [1, 1, 2, 2, 3, 3]
p arr.flat_map(&method(:fn))  #=> [[1], [1], [2], [2], [3], [3]]
def flat_map(arr)
  arr.map{|el| yield el}.flatten(1)
end

def fn(v)
  [v, v]
end

arr1 = [[1], [2], [3]]

p flat_map(arr1, &method(:fn)) == arr1.flat_map(&method(:fn)) #=> true

arr2 = [[1, [2, 3]], [[4,5], 6], [7]]

p flat_map(arr2, &method(:fn)) == arr2.flat_map(&method(:fn)) #=> true

とすれば、Enumerable#flat_mapと同じ、になりそうですね。

7
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?