[swift-users] Comparing POP to OOP

Dave Abrahams dabrahams at apple.com
Tue Mar 8 12:40:59 CST 2016


on Mon Mar 07 2016, Jon Hoffman <hoffman.jon-AT-gmail.com> wrote:

>> On Mar 7, 2016, at 6:15 PM, Dave Abrahams <dabrahams at apple.com> wrote:
>> 
>> 
>> on Mon Mar 07 2016, Jon Hoffman <hoffman.jon-AT-gmail.com <http://hoffman.jon-at-gmail.com/>> wrote:
>> 
>
>>>> On Mar 6, 2016, at 11:53 PM, Dave Abrahams <dabrahams at apple.com> wrote:
>>>> 
>>>> 
>>>> on Sun Mar 06 2016, Jon Hoffman <hoffman.jon-AT-gmail.com> wrote:
>>>> 
>>> 
>>>>>> 
>>>> 
>>>> “Protocol-oriented” doesn't mean “no reference types.”  It means you're
>>>> not forced into reference semantics just because you want polymorphism.
>>>> 
>>>>> For example we cannot create a linked list with a value type.
>>>> 
>>>> Not true, in fact.
>>>> 
>>>> enum List<T> {
>>>>    case Empty
>>>>    indirect case NonEmpty(T, List)
>>>> } 
>>>> 
>>>> var x: List = .NonEmpty(3, .NonEmpty(4, .Empty))
>>>> 
>>>> There are other ways, but that's the simplest in Swift.
>>> 
>>> I stand corrected; I neglected to think about using the enumeration.
>> 
>> Note again: there are other ways, e.g. you can make it immutable or
>> build it with COW.
>
> So for the last two hours or so I put myself on a task to create a
> mutable linked list using value types and to do it in an elegant way
> (Hey I love challenges and beating my head against the wall).  

A linked list that conforms to MutableCollection with the right
efficiency characteristics for linked lists *and* value semantics is a
tough problem.

I think under the proposed new indexing model you can just build it on
top of an Array, though ;-)

> While I have found one working solution so far it is pretty ugly
> therefore I have to ask myself, that even though it is preferred that
> we use value types overall, should it be preferred that we use
> reference types for mutable data structures like this?  

What do you mean by “like this?”  Array is a mutable data structure; is
it “like this?”

You're going to use reference types in the *implementation* of any type
that has arbitrary growth.  Array uses a reference internally.

> Trust me, I have not giving up finding an elegant solution yet just
> wondering your thoughts on that.

My feeling is that linked lists are almost never the best answer in
real programs, but if you *really* need their characteristics you
might want to implement them with reference semantics.

-- 
-Dave


More information about the swift-users mailing list