Last active
August 29, 2015 14:05
-
-
Save rnapier/7321b964497cbc779b7b to your computer and use it in GitHub Desktop.
Generics do not compose (is that the right way to think about it?)
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
// Generics do not compose | |
// The generic f() | |
func f<T>(x: T) -> T { return g(x) } | |
// The every-day g() that f() calls | |
func g<T>(x: T) -> T { | |
return x | |
} | |
// A special thing that some types can do | |
protocol Doubleable { | |
func double() -> Self | |
} | |
// String is one of those types | |
extension String : Doubleable { | |
func double() -> String { | |
return self + self | |
} | |
} | |
// And a special g() for types that can do that special thing | |
func g<T:Doubleable>(x: T) -> T { | |
return x.double() | |
} | |
// Let's see what we call | |
f(1) // => 1 | |
f([1]) // => [1] | |
g("this") // => "thisthis" (Here, we specialize to the Doubleable g()) | |
f("this") // => "this" (should be "thisthis", since String is Doubleable) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment