Skip to content

Instantly share code, notes, and snippets.

@ikesyo
Created June 5, 2014 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikesyo/9a2a6dd683f0382b804d to your computer and use it in GitHub Desktop.
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
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