作者:爱夫777 | 来源:互联网 | 2023-08-17 19:25
Ivebeenlookingatsomecodeexamplesfromanotherlanguage(Haskell&C#tobespecific),and
I've been looking at some code examples from another language (Haskell & C# to be specific), and I'm having an issue coming up with a Swift equivalent.
我一直在研究另一种语言的一些代码示例(Haskell和C#是具体的),而我遇到了一个与Swift等价的问题。
From the Haskell definition, we have:
根据Haskell定义,我们有:
data Tr a = Lf a | Br (Tr a) (Tr a)
From C#, we have:
从C#开始,我们有:
public abstract class Tr { }
public class Lf : Tr {
public a contents { get; set; }
}
public class Br : Tr {
public Tr left { get; set; }
public Tr right { get; set; }
}
So a Tree is either a Leaf with a content of a generic type, or a Branch with a left & right Tree.
因此,Tree可以是具有泛型类型内容的Leaf,也可以是具有左右树的分支。
I'm bumping up against the type system in Swift, so I'm not sure what the appropriate form should be. I have:
我碰到了Swift中的类型系统,所以我不确定应该采用什么样的形式。我有:
protocol Tree {
associatedtype Element: CustomStringConvertible
}
struct Leaf: Tree {
typealias Element = LeafElement
let content: Element
}
struct Branch: Tree {
typealias Element = BranchElement
let left: Tree
let right: Tree
}
At this point, the above is many iterations of banging my head against the wall, so it's probably way off at this point. Leaf seems to be fine, but Branch fails with
在这一点上,上面是我的头撞墙的许多次迭代,所以在这一点上它可能已经过时了。 Leaf看起来很好,但Branch失败了
Protocol 'Tree' can only be used as a generic constraint because it has Self or associated type requirements
And recommendations would be appreciated.
建议将不胜感激。
1 个解决方案