Created
August 24, 2014 20:22
-
-
Save pyrtsa/2bbc9057d595dd7ea27a to your computer and use it in GitHub Desktop.
Trying to represent generic trees in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class Box<T> { | |
private let _value: () -> T | |
public init(_ value: T) { self._value = {value} } | |
public var value: T { return _value() } | |
} | |
enum Tree1<T> { | |
case Leaf(T) | |
case Left(Tree1<T>, T) | |
case Right(T, Tree1<T>) | |
case Both(Tree1<T>, T, Tree1<T>) | |
} | |
//=> swiftc segfaults with no explanation | |
// (I would have expected an error message saying that recursive value types aren't supported.) | |
enum Tree2<T> { | |
case Leaf(T) | |
case Left(Box<Tree2<T>>, T) | |
case Right(T, Box<Tree2<T>>) | |
case Both(Box<Tree2<T>>, T, Box<Tree2<T>>) | |
} | |
//=> swiftc segfaults with a trace containing: | |
// "(...) While emitting IR SIL function @_TFO4Tree5Tree24LeftU__fMGS0_Q__FTGCS_3BoxGS0_Q___Q__GS0_Q__ for 'Left' (...)" | |
enum Tree3<T> { | |
case Leaf(Box<T>) | |
case Left(Box<Tree3<T>>, Box<T>) | |
case Right(Box<T>, Box<Tree3<T>>) | |
case Both(Box<Tree3<T>>, Box<T>, Box<Tree3<T>>) | |
} | |
//=> This seems to work! | |
// The following compiles and runs. (Would of course make it easier to use with custom init etc.) | |
let leaf = Tree3<Int>.Leaf(Box(1)) | |
let left = Tree3<Int>.Left(Box(leaf), Box(2)) | |
let right = Tree3<Int>.Right(Box(3), Box(left)) | |
let both = Tree3<Int>.Both(Box(leaf), Box(4), Box(left)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment