Intuitively, peek returns the same value as pop, but does not change the data. Behavior when the collection is empty varies – most often this yields an underflow error, identically to a pop on an empty collection, but some implementations provide a function which instead simply returns (without error), essentially implementing if isempty then return, else peek.
This behavior can be axiomatized in various ways. For example, a common VDM (Vienna Development Method) description of a stack defines
top (peek) and
remove as atomic, where
top returns the top value (without modifying the stack), and
remove modifies the stack (without returning a value).
[1] In this case
pop is defined in terms of
top and
remove.Alternatively, given
pop, the operation
peek can be axiomatized as:
peek(
D) =
pop(
D)
peek(
D),
D =
Dmeaning "returns the same value as
pop", and "does not change the underlying data" (value of data after peek same as before peek).