我试着得到一种深度平坦的方法
[ 1, [2], [[3]] ] => [1, 2, [3]][ 1, 2, [[3]] ] => [1, 2, [3]][[1, [[2, 3]]]] => [1, [[2, 3]]][1, 2] => [1, 2]
更新我的代码到
def flatten(array)
result = [] of typeof(array) | typeof(array.first)
array.each do |item|
if item.is_a?(Array)
result = ([] of typeof(item) | typeof(item.first)) + result
result.concat(item)
else
result << item
end
end
result
end但是平面(1,2)未能引发异常https://play.crystal-lang.org/#/r/3p6h
发布于 2018-03-10 22:53:58
为了安全起见,需要数组类型及其元素类型的联合:
def unwrap(array)
result = [] of typeof(array)|typeof(array.first)
array.each do |item|
if item.is_a?(Array)
result.concat item
else
result << item
end
end
result
endhttps://stackoverflow.com/questions/49213864
复制相似问题