Skip to content

Instantly share code, notes, and snippets.

@jhaberstro
Last active June 3, 2016 12:17
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhaberstro/1a1787c701d0e2285919 to your computer and use it in GitHub Desktop.
Save jhaberstro/1a1787c701d0e2285919 to your computer and use it in GitHub Desktop.
Swift typeclass example
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