Accumulators are variables or data structures used to store intermediate results during computations. They are commonly used in programming to aggregate values, such as summing numbers, counting occurrences, or collecting items in a list.
In functional programming, an accumulator is often used in recursive functions to carry the accumulated result through the recursive calls.
Here’s a simple example in Python that demonstrates an accumulator in a function that sums a list of numbers:
def sum_list(numbers, accumulator=0):
if not numbers:
return accumulator
else:
return sum_list(numbers[1:], accumulator + numbers[0])
# Example usage
numbers = [1, 2, 3, 4, 5]
result = sum_list(numbers)
print(result) # Output: 15
In this example, accumulator keeps track of the sum as the function processes each element of the list.
