In programming languages and type theory, polymorphism is the provision of a single interface to entities of different types. A polymorphic type is one whose operations can also be applied to values of some other type, or types. Wikipedia Polymorphism [email protected]
Type class in Haskell class Eq a where (==), (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) instance Eq Integer class x == y = x `integerEq` y [email protected]
Type class in Swift protocol Eq { associatedtype T func equalTo(other: T) -> Bool } extension Int : Eq { typealias T = Int func equalTo(other: T) -> Bool { return self == other } } [email protected]
Type class in Swift protocol Eq { func equalTo(other: Self) -> Bool } extension Int : Eq { func equalTo(other: Int) -> Bool { return self == other } } let i = 1 let j = 1 print(i.equalTo(j)) // => true [email protected]
func encodeInCeasar(c: C) -> String { return C.toCeasar(c) } print(encodeInCeasar(1234)) //=> 4567 print(encodeInCeasar("abcd")) //=> defg print(encodeInCeasar(1.234)) //=> Cannot invoke 'encodeInCeasar' with an argument list of type '(Double)' Example: Caesar cipher [email protected]
References • WWDC 2015 session “Protocol-Oriented Programming in Swift” https://developer.apple.com/videos/play/wwdc2015/408/ • Typeclasses in Swift, Haskell and Scala https://touk.pl/blog/2015/09/14/typeclasses-in-swift/ • Typeclass in Swift and Scala http://www.danishin.com/article/Typeclass_in_Swift_and_Scala • Associated types vs. type parameters - reason for the former? https://devforums.apple.com/thread/230611 • Swift Generic Protocols https://milen.me/writings/swift-generic-protocols/ • Swift: Associated Types http://www.russbishop.net/swift-associated-types [email protected]