首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >纵深一平阵

纵深一平阵
EN

Stack Overflow用户
提问于 2018-03-10 20:45:24
回答 1查看 73关注 0票数 1

我试着得到一种深度平坦的方法

[ 1, [2], [[3]] ] => [1, 2, [3]] [ 1, 2, [[3]] ] => [1, 2, [3]] [[1, [[2, 3]]]] => [1, [[2, 3]]] [1, 2] => [1, 2]

更新我的代码到

代码语言:javascript
复制
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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-10 22:53:58

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

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49213864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档