Swift中使用泛型的递归枚举

Kua*_*hou 5 recursion enums swift

我是Swift的新手.我试图用递归枚举和泛型实现二叉树:

enum BinaryTree<T> {
  indirect case Node(T, BinaryTree<T>, BinaryTree<T>)
  case Nothing
}

func inorder<T>(_ root: BinaryTree<T>) -> [T] {
  switch root  {
  case .Nothing: 
    return []
  case let .Node(val, left, right):
    return inorder(left) + [val] + inorder(right) 
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

$ swift ADT.swift 
ADT.swift:83:20: error: cannot convert value of type 'BinaryTree<T>' to expected argument type 'BinaryTree<_>'
    return inorder(left) + [val] + inorder(right) 
                   ^~~~
Run Code Online (Sandbox Code Playgroud)

但是,这有效:

func inorder<T>(_ root: BinaryTree<T>) -> [T] {
  switch root  {
  case .Nothing: 
    return []
  case let .Node(val, left, right):
    let l = inorder(left) 
    let r = inorder(right)
    return l + [val] + r
  }
}
Run Code Online (Sandbox Code Playgroud)

我的语法有错吗?谢谢!

我正在使用Swift 3.0.

thm*_*thm 1

更新
\n因此,我尝试将问题压缩为无法编译的最小示例代码,并自己提出了一个问题并提交了SR-4304。事实证明,这确实是编译器中的一个错误。

\n\n

原始答案
\n据我所知,您的语法完全有效。看来 Swift 编译器\xe2\x80\x99s 类型推断似乎需要在第二个解决方案显然提供的正确方向上推动。由于我过去遇到过几个类似的问题,特别是有关+运算符的问题,因此您的问题启发我尝试其他几种加入数组的方法。这些都有效(我只是显示最后三种情况的返回语句和支持函数):

\n\n
return (inorder(left) as [T]) + [val] + inorder(right)\nreturn Array([inorder(left), [val], inorder(right)].joined())\nreturn [inorder(left), [val], inorder(right)].reduce([], +)\nreturn [inorder(left), [val], inorder(right)].flatMap { $0 }\n\nfunc myjoin1<T>(_ arrays: [T]...) -> [T]\n{\n    return arrays.reduce([], +)\n}\nreturn myjoin1(inorder(left), [val], inorder(right))\n\nfunc myjoin2<T>(_ array1: [T], _ array2: [T], _ array3: [T]) -> [T]\n{\n    return array1 + array2 + array3\n}\nreturn myjoin2(inorder(left), [val], inorder(right))\n\nextension Array\n{\n    func appending(_ array: [Element]) -> [Element]\n    {\n        return self + array\n    }\n}\nreturn inorder(left).appending([val]).appending(inorder(right))\n
Run Code Online (Sandbox Code Playgroud)\n\n

将运算符作为函数调用也可以编译:

\n\n
return (+)(inorder(left), [val]) + inorder(right)\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果对 Swift 编译器有更深入了解的人能够对此有所了解,那就太好了。

\n