Search code examples
eiffeleiffel-studio-18

How do I initialize and fill a linked list in Eiffel?


Here's what I have so far.

create {LINKED_LIST[INTEGER]} list.make
from
    i := 0
    list.start
until
    i = 11
loop
    list.put(i)
    i := i + 1
    list.forth
end

The debugger points to line list.put(i). I think the problem is that list is not properly initialized? I'm having a bit of an issue with figuring out how to use linked_list because I can't find any proper tutorial to help with. As you can see, I am just trying to write a LINKED_LIST program that adds numbers [0,10] in a linked list. Not a school project. Just practicing ahead of an upcoming course. Please help!


Solution

  • Let's look at the comments of the features that are used in the original example:

    1. LIST.put (v: like item): Replace current item by v.
    2. LIST.start: Move cursor to first position.
    3. LIST.forth: Move to next position.

    The newly created list is empty. Therefore, there are no items that can be replaced by calling put. This explains why the debugger stops at the feature put: the precondition of the feature is violated.

    Looking at the interface view of the class LIST, there is a feature clause Element change with the following features:

    • append (s: SEQUENCE [G]): Append a copy of s.
    • extend (v: G): Add a new occurrence of v.
    • fill (other: CONTAINER [G]): Fill with as many items of other as possible.
    • force (v: like item): Add v to end.
    • put (v: like item): Replace current item by v.
    • sequence_put (v: like item): Add v to end.
    • put_i_th (v: like item; i: INTEGER_32): Put v at i-th position.
    • replace (v: G): Replace current item by v.

    Because we are talking about a feature to add a new element to the end of the list, only the following ones are suitable: extend, force, sequence_put. The idiomatic feature name for this case is extend.

    Taking this into account, the original loop becomes:

    from
        i := 0
    until
        i = 11
    loop
        list.extend (i)
        i := i + 1
    end