SECTION 23 / 24

Tutorial: implement length, first and last

1 min read
List functions have different return types and boundary conditions. first and last need an element to return; length([]) is 0.
List functions have different return types and boundary conditions. first and last need an element to return; length([]) is 0.
REAL COURSE DATA · BUILD AND UNPACK LISTS

Trace length, first, last, rest and init

Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change, then step through the list. The original course records remain unchanged.

Procedure length(L):
    Count = 0
    foreach x in L:
        Count = Count + 1
    return Count

Procedure first(L):
    # Precondition: L is non-empty
    foreach x in L:
        return x

Procedure last(L):
    # Precondition: L is non-empty
    foreach x in L:
        E = x
    return E

length accepts a list and returns its occurrence count. The empty list returns 0 because no increment occurs. first returns during the very first loop execution, which terminates the function. last overwrites E on every visit, so after the final visit E holds the final element.

first([]) has no first occurrence; last([]) never assigns E. The tutorial calls both results undefined. State a non-empty precondition or add an explicit error/unavailable result. Do not invent a return value of 0 or [] for an undefined element. Different implementations may share the same interface but use different amounts of work.

Try it yourself

How many foreach visits does this first implementation need on a non-empty list?

Show explained answer

One. The first return stops the function immediately.

Try it yourself

Does last have to visit the entire list in this implementation?

Show explained answer

Yes. E must be overwritten by each element until the final one. Other representations may offer a different implementation.

Try it yourself

What is length([3,3,25])?

Show explained answer

3, because length counts occurrences, not distinct values.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑