swift - Custom Collections Without Internal Collection Types? -
i'd learn more swift's collection types creating custom collection.
the problem can't find examples of "custom" collection types don't use internal array / dictionary.
these aren't helpful me, because when comes time conform collection protocol, examples propagate required methods army / dictionary.
that said, after looking through wikipedia's list of data structures, can't find meet performance characteristics of collection types, aren't specialized arrays.
does know of data structure implemented custom collection type, without using internal collection type?
edit
collection protocol conformance requires accesing startindex, endindex,and elements of collection done constant time - o(1).
edit 2
the consensus in comments seems linkedlist data structure satisfies these characteristics. linkedlist defined follows:
indirect enum linkedlist<t> { case value(element: t, next: linkedlist<t>) case end } extension linkedlist: sequence { func makeiterator() -> linkedlistiterator<t> { return linkedlistiterator(current: self) } } struct linkedlistiterator<t>: iteratorprotocol { var current: linkedlist<t> mutating func next() -> t? { switch current { case let .value(element, next): current = next return element case .end: return nil } } }
what still don't understand, how subscript
can returned in constant time. linkedlist:
let data = linkedlist<int>.value(element: 0, next: linkedlist<int>.value(element: 1, next: linkedlist<int>.value(element: 2, next: linkedlist<int>.value(element: 3, next: linkedlist<int>.end))))
assume want access 3rd element in collection:
let example = data[2]
currently, how have implemented subscript:
subscript (position: index) -> element { precondition(position < endindex && position >= startindex) var iterator = makeiterator() in 0 ..< position { iterator.next() if + 1 == position { return iterator.next()! } } var 0 = makeiterator() return zero.next()! }
because method's completion time depends on `i, finishes in linear rather constant time. how such constant time method implemented?
Comments
Post a Comment