深度一展平数组

Flatten array in depth one

我尝试获得一种深度展平方法

[ 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

但是 flatten([1, 2]) 未能引发异常 https://play.crystal-lang.org/#/r/3p6h

https://github.com/crystal-lang/crystal/issues/5805

为了安全起见,您需要数组类型及其元素类型的联合:

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
end