> On May 27, 2016, at 1:12 AM, Thorsten Seitz <[email protected]> wrote:
> 
>> Am 26.05.2016 um 22:07 schrieb Matthew Johnson via swift-evolution 
>> <[email protected] <mailto:[email protected]>>:
>> 
>>> 
>>> 
> 
> 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

_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to