[swift-evolution] Enhanced existential types proposal discussion

Austin Zheng austinzheng at gmail.com
Fri May 27 03:17:50 CDT 2016


> On May 27, 2016, at 1:12 AM, Thorsten Seitz <tseitz42 at icloud.com> wrote:
> 
>> Am 26.05.2016 um 22:07 schrieb Matthew Johnson via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>>:
>> 
>>> 
>>> 
> 
> With Joe’s information about unbound associated types still being usable, e.g. as `a.Element` with the current proposal we should actually already have existential types like defined in Wikipedia or Haskell (except for the name "existential“ being used differently in Swift, e.g. for protocols without associated types, too).
> 
> protocol T {
> 	associatedtype X
> 	var a: X { get }
> 	func f(_ value: X) -> Int
> }
> 
> // use T as existential in Wikipedia’s sense
> func foo(t: any<T>) -> Int {
> 	return t.f(t.a)  // t.X is not bound to a fixed type but as it is used consistently it works for any T
> }

Yes, this is the key insight. The types aren't known at runtime, but they are used in a manner that is guaranteed to be sound. (Whatever the type of X is, if you get it as an output from "a" you should be able to pass it into "f").

> 
> 
> struct A : T {
> 	var a: Int
> 	func f(_ value: Int) -> Int { return value }
> }
> 
> struct B : T {
> 	var a: String
> 	func f(_ value: String) -> Int { return value.characters.count }
> }
> 
> let a = A(a: 42)
> let b = B(a: "hello")
> let x = foo(a) // 42
> let y = foo(b) // 5
> 
> 
> Actually in this case we could have written foo() also as generic function (without having to bind X!)
> 
> func foo<P: T>(t: P) -> Int {
> 	return t.f(t.a)
> }
> 
> This works already today.

Once opening existentials enters the language (which would allow two or more existentials to compare their self types and associated types), I think existentials become almost equivalent in power to generics in Swift.

> 
> 
> -Thorsten

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160527/2070a71a/attachment.html>


More information about the swift-evolution mailing list