原です。
In message "[ruby-list:10395] Re: array"
on 98/10/28, Shin-ichro Hara <sinara / blade.nagaokaut.ac.jp> writes:
|原です。
|def tensor(n = nil, *sizes)
| return yield unless n
| (0..n-1).collect { |i|
| tensor(*sizes) { |*x| yield(i, *x) }
| }
|end
悪ノリして「超 Enumerable」というのを考えて見ました。
超 Enumerable とは、Enumerable でかつ each で出てくる各要素が
また Enumerable であるものです。
そして、後は「超 each」、「超 collect」などを作るわけです。
例えば、
#module SuperEnumerable
module Enumerable
def s_each
if size == 0
yield
else
a, *b = to_a
a.each { |i| b.s_each{ |*x| yield(i, *x) } }
end
end
def s_collect
if size == 0
yield
else
a, *b = to_a
a.collect { |s| b.s_collect{ |*x| yield(s, *x) } }
end
end
end
# で、もとの問題であった多重配列の生成はこんな感じでできる。
dat = [0..2, 0..3, 0..4].s_collect { |*x| x }
# テスト
class Array
def at(*x)
n, *x = x
if x.size == 0
self[n]
else
self[n].at(*x)
end
end
end
[0..2, 0..3, 0..4].s_each { |*x| p dat.at(*x) }
# s_collect は s_each から派生させるべきかな。
#「超」ではなく「多重」と呼ぶ方がいいのかな。