Created
January 12, 2018 09:32
-
-
Save bkase/7139a80f28ce6b465a71b0b38360fbd2 to your computer and use it in GitHub Desktop.
"Gadts" with a base protocol
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
protocol Expr { | |
associatedtype A | |
func eval() -> A | |
} | |
struct Const<T>: Expr { | |
typealias A = T | |
let value: A | |
func eval() -> A { | |
return value | |
} | |
} | |
struct Add<E1: Expr, E2: Expr>: Expr where E1.A == Int, E2.A == Int { | |
typealias A = Int | |
let lhs: E1 | |
let rhs: E2 | |
func eval() -> Int { | |
return lhs.eval() + rhs.eval() | |
} | |
} | |
struct Equal<E1: Expr, E2: Expr>: Expr where E1.A == Bool, E2.A == Bool { | |
typealias A = Bool | |
let lhs: E1 | |
let rhs: E2 | |
func eval() -> Bool { | |
return lhs.eval() == rhs.eval() | |
} | |
} | |
let x = Add(lhs: Const(value: 1), rhs: Const(value: 2)) | |
print(type(of: x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment