Last active
June 3, 2016 12:17
-
-
Save jhaberstro/1a1787c701d0e2285919 to your computer and use it in GitHub Desktop.
Swift typeclass example
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 { | |
class func zero() -> Self | |
func succ() -> Self | |
func add(y: Self) -> Self | |
func multiply(y: Self) -> Self | |
} | |
extension Int32: Num { | |
static func zero() -> Int32 { return 0 } | |
func succ() -> Int32 { return self + 1 } | |
func add(y: Int32) -> Int32 { return self + y } | |
func multiply(y: Int32) -> Int32 { return self * y } | |
} | |
func sum<A : Num>(xs: Array<A>) -> A { | |
return xs.reduce(A.zero(), { $0.add($1) }) | |
} | |
let l : Array<Int32> = [1,2,3] | |
println(sum(l)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment