[swift-evolution] Adding an operator to return the "lowest common type" of two types?

Martin Kühl martin.kuehl at gmail.com
Mon Dec 7 04:20:40 CST 2015


On 7 December 2015 at 10:53, William Shipley via swift-evolution <
swift-evolution at swift.org> wrote:

> The problem I’m trying to solve is if I have
>
> class LineSegmentObject {
> ...
> }
> class Wall : LineSegmentObject {
> ...
> }
> class Ray : LineSegmentObject {
>> }
>
> And then in my code if I have
>
>         let wallsInBounds: Set<Wall> = …
>         let raysOffWalls: Set<Ray> = ...
>
>         let unionOfAllTestedLineSegmentObjects =
> wallsInBounds.union(raysOffWalls)
>
>
> it fails to compile. Instead I have to do the very ugly
>
>         var unionOfAllTestedLineSegmentObjects: Set<LineSegmentObject> =
> (raysOffWalls as Set<LineSegmentObject>).union(wallsInBounds as Set<
> LineSegmentObject>)
>
> As an aside, this also fails, surprisingly to me:
>
>         var unionOfAllTestedLineSegmentObjects = Set<LineSegmentObject>()
>         unionOfAllTestedLineSegmentObjects.unionInPlace(wallsInBounds)
>
>>
> So, what if we had an operator called, say, “commonType” that could take
> two types and return the closest type the both have in common?
>
> Then the union operator for Set (and similar operators in Array and
> Dictionary) could look something like:
>
>     public func union<S : SequenceType>(sequence: S) -> Set<commonType(Element,
> S.Generator.Element)>
>
> instead of:
>
>     public func union<S : SequenceType where S.Generator.Element ==
> Element>(sequence: S) -> Set<Element>
>
> [sorry if I got the syntax of defining a generic wrong up there, I’m still
> new to this)
>
> So we’d automatically get an Set of LineSegments if we union a Set of Rays
> with a Set of Walls, which is what I’d expect.
>

I think I like the idea, but I don’t think we should need a dedicated
operator for this.
How do you feel about a declaration like this:

    func union<S: SequenceType, E where Element: E, S.Generator.Element:
E>(sequence: S) -> Set<E>

Martin

—
> If this type of thing doesn’t seem strict enough for you, then it could
> also just be a separate function, like “heterogenousUnion()” instead of
> “union()”.
>
> Also, I believe this could make it a LOT easier to build heterogenous
> Dictionaries in code, which I actually can’t do at all in the current
> Swift. (Eg, creating dictionaries with arbitrary types of keys and values
> that you might feed to, say, SCNTechnique.) And it’d make dealing with
> mixed Arrays easier in a similar way.
>
> --
>
> On a scale from “Lattner" to “Lohan,” how bad an idea is this?
>
> -Wil
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/d34eac5e/attachment.html>


More information about the swift-evolution mailing list