Created
June 5, 2014 13:20
-
-
Save ikesyo/9a2a6dd683f0382b804d to your computer and use it in GitHub Desktop.
Extensions version of http://maxs.io/typeclass-encoding-in-swift/ instead of explicit type class instance
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 Num { | |
typealias N | |
class func zero() -> N | |
func succ() -> N | |
func add(other: N) -> N | |
func multiply(other: N) -> N | |
} | |
extension Int8: Num { | |
typealias N = Int8 | |
static func zero() -> N { return 0 } | |
func succ() -> N { return self + 1 } | |
func add(other: N) -> N { return self + other } | |
func multiply(other: N) -> N { return self * other } | |
} | |
extension Int32: Num { | |
typealias N = Int32 | |
static func zero() -> N { return 0 } | |
func succ() -> N { return self + 1 } | |
func add(other: N) -> N { return self + other } | |
func multiply(other: N) -> N { return self * other } | |
} | |
func sumVec<A: Num where A.N == A>(xs: Array<A>) -> A { | |
return xs.reduce(A.zero()) { $0.add($1) } | |
} | |
let xs8: Array<Int8> = [0, 1, 4, 8] | |
let xs32: Array<Int32> = [0, 1, 4, 8] | |
let q = sumVec(xs8) // 13 | |
let r = sumVec(xs32) // 13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment