4 ms·
> For example, one would often like an IIndexable interface to cover both arrays and lists I’ve thought about this. To be useful, an IIndexable would need get
by noblethrasher 12y ago
> For example, one would often like an IIndexable interface to cover both arrays and lists
I’ve thought about this.
To be useful, an IIndexable would need get and set methods for the index, and a Length/Count property. You would need to explicitly implement it on something like the array class since you wouldn’t want to lose the semantic difference between Length (O(1)) and Count (O(n)).
But, the existence of Func<T, TResult> and Action<T1, T2> would largely obsolete the utility of such and interface.
Let xs be an “indexable” object of T (e.g. T[] or List<T>). Then any method that expects to only access an object could just accept lambda of type int -> T. So, you’d just pass it
n => xs[n].
Similarly, methods that expect to mutate the object could take a lambda of type (int, T) -> (). So would just pass something like
(n, x) => xs[n] = x.
This is nicer because it makes explicit what the method will do to the indexable.
- danbruc 12y agoI don't think there is the distinction between Length and Count you draw - Count is O(1) for most collections, even LinkedList<T> maintains the number of elements in the list in a separate field. You could say Length does not change during the lifetime of an object while Count may do so, but I am not even sure if this distinction is always honored.
- noblethrasher 12y agoYes, I think you're right. I thought that I had read stuff about the name implying the complexity class, but my Google-Fu isn't turning anything up.