Created
February 26, 2022 08:36
-
-
Save oliverepper/ec0c055879d86c008ceef32406aba5ec to your computer and use it in GitHub Desktop.
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
import Foundation | |
struct Output: TextOutputStream { | |
mutating func write(_ string: String) { | |
print(string, terminator: "") | |
} | |
} | |
protocol Drawable { | |
func draw_(out: inout Output, position: Int) | |
} | |
struct object_t { | |
struct model<T>: Drawable { | |
private let data_: T | |
init(_ x: T) { | |
data_ = x | |
} | |
func draw_(out: inout Output, position: Int) { | |
draw(data_, out: &out, position: position) | |
} | |
} | |
fileprivate let self_: Drawable | |
init<T>(_ x: T) { | |
self_ = model(x) | |
} | |
} | |
typealias document_t = Array<object_t> | |
extension document_t { | |
mutating func append<T>(_ x: T) { | |
self.append(object_t(x)) | |
} | |
} | |
func draw<T>(_ x: T, out: inout Output, position: Int) { | |
if let document = x as? document_t { | |
draw(document, out: &out, position: position) | |
return | |
} | |
print(String(repeating: " ", count: position), x, to: &out) | |
} | |
func draw(_ x: object_t, out: inout Output, position: Int) { | |
x.self_.draw_(out: &out, position: position) | |
} | |
func draw(_ x: document_t, out: inout Output, position: Int) { | |
print(String(repeating: " ", count: position), "<document>", to: &out) | |
for elem in x { draw(elem, out: &out, position: position + 2) } | |
print(String(repeating: " ", count: position), "</document>", to: &out) | |
} | |
var document = document_t() | |
document.append(1) | |
document.append("Zwei") | |
document.append(document) | |
document.append(false) | |
var out = Output() | |
draw(document, out: &out, position: 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment