Cocoa semantics
Cocoa semantics
- Subject: Cocoa semantics
- From: Tom Davie <email@hidden>
- Date: Fri, 16 Jul 2004 20:00:44 +0100
Hi,
I've been writing a very basic linked list class in Objective-C, and
have been having trouble thinking out exactly what the correct
semantics for a linked list is when using Objective-C. I am starting
looking at the list from a functional programming standpoint in which
the semantics are easy. You simply have two constructions: the empty
list (denoted []); and a method of constructing a new list from an
item and another list (denoted ':'), so for example the list
containing 2, 5, and 7 is made up by starting with the empty list ([])
adding 7 to it (7:[]), adding 5 to it (5:(7:[])), and then adding 2 to
it (2:(5:(7:[]))). Because this is a functional paradigm, there is no
state, so when you add 2 to the list, you loose access to what you had
before and (5:(7:[])) no longer exists on it's own - instead it is
only the tail of the new list.
When looking at this from the point of view of Objective-C, things
become quite a bit more complex. If we are to simply duplicate the
behavior of the functional model then we hit a problem. The empty
list constructor is relatively easy b we simply write something like
this:
+ (id)emptyList
{
return [[[LinkedList alloc] init] autorelease];
}
The cons operator though (:) is more complex, because after the
operation has happened we still have access to the tail end of the
list by other means i.e. if we have a linked list a and we then say b
= [LinkedList cons:newItem to:a];, we still have access to a, so then
doing [a removeItemAtIndex:5]; also has the side effect of removing
something from b. After much thought I think that I have found the
correct semantics for the class, but I wanted to check if my thoughts
matched those of the rest of the cocoa world. The conclusion I have
come to is that a class operator similar to cons should be provided,
but should in fact copy the old list, so b=[LinkedList cons:newItem
to:a]; would in fact create two entirely separate lists a and b, where
the contents of a also happen to be the contents of b (b having the
extra element newItem). Secondly, an object method should be provided
that would work as [a addItemToFront:newItem]; which simply modifies a
to be a list with newItem added first (much like cons, but not
returning the new list, instead modifying the original).
Your thoughts would be much appreciated.
Thanks
Tom Davie
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.