Search code examples
eiffel

LINKED_LIST indexing from 0, not 1, possible?


In eiffel, indexing usually starts from 1, not 0.

I have following 2 attributes:

arr: ARRAY[A]

link: LINKED_LIST[B]

For array, I can make its indexing starts from 0 purposely, like following:

arr.force (value, arr.count)

so that arr[0] will be readable.

However, I did similar thing to LINKED_LIST:

link.put_i_th (value, link.count)

However this gets precondition violation.

Is there any way to make LINKED_LIST indexing from 0, not 1? so that link[0] will be accessible?

I need an example if it is possible.


Solution

  • The precondition valid_key of put_i_th in LINKED_LIST (as well as in a more general LIST) is specified using a function valid_index. The behavior of the latter can be derived from its postcondition Result = (i >= 1 and i <= count). It states that a valid index is greater than zero.

    The boundaries of containers are also available as queries lower and upper. For a LIST the value of lower is a constant 1.

    From the observations above it follows that a LIST (and a LINKED_LIST) cannot have elements at index 0 (or below).

    Also, unlike an ARRAY, where the size of the structure is controlled directly, elements to a LIST are added one-by-one. That's why force in LIST has no index and works like extend that adds a new element to the end of the structure.

    Although ARRAY allows indexing from 0 (or any other integer value), it's considered a bad practice to use a lower index other than 1 because most containers have lower = 1. Only in rare cases when the code can benefit from indexes starting from something different from 1, it might make sense to deviate from the standard convention.