Ready to begin
No records have been processed. Start with Next step.
![List functions have different return types and boundary conditions. first and last need an element to return; length([]) is 0.](/images/computational-thinking/week-5/list-functions.png)
Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.
Ready
No records have been processed. Start with Next step.
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 Elength 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.
How many foreach visits does this first implementation need on a non-empty list?
One. The first return stops the function immediately.
Does last have to visit the entire list in this implementation?
Yes. E must be overwritten by each element until the final one. Other representations may offer a different implementation.
What is length([3,3,25])?
3, because length counts occurrences, not distinct values.