Skip to content

Instantly share code, notes, and snippets.

@llibra
Last active August 7, 2016 06:48
Show Gist options
  • Save llibra/f39ee0f6a0f5af5d5a498c6e812ccef9 to your computer and use it in GitHub Desktop.
Save llibra/f39ee0f6a0f5af5d5a498c6e812ccef9 to your computer and use it in GitHub Desktop.
Algebraic data type in Swift.
// cf. https://ja.wikipedia.org/wiki/%E4%BB%A3%E6%95%B0%E7%9A%84%E3%83%87%E3%83%BC%E3%82%BF%E5%9E%8B
enum Node {
case leaf(Int)
indirect case branch(Node, Node)
}
func dump(node: Node) {
func iter(node: Node) {
switch node {
case let .leaf(x):
print(x, terminator: "")
case let .branch(left, right):
print("(", terminator: "")
iter(left)
print(" . ", terminator: "")
iter(right)
print(")", terminator: "")
}
}
iter(node)
print()
}
dump(.leaf(1))
// 1
dump(.branch(.leaf(1), .leaf(2)))
// (1 . 2)
dump(.branch(.branch(.leaf(1), .leaf(2)), .leaf(3)))
// ((1 . 2) . 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment