Sometimes you need to work with lists of a fixed length, or compute a running total from a series of values. Let’s look at how to do both in Elixir using a short, practical example.
Suppose you start with this list:
list = [19, 21, 27, 16, 37, 34, 27, 32, 33, 10]
Padding a list to a fixed length
You can easily extend this list to a fixed size (e.g. 12 elements) by adding zeros until it reaches the desired length:
target_length = 12
pad = max(target_length - length(list), 0)
list = list ++ List.duplicate(0, pad)
Here’s what happens:
length(list)
gets the current size.target_length - length(list)
calculates how many zeros are needed.List.duplicate(0, pad)
creates a list with that many zeros.- Finally,
list ++ ...
concatenates them together.
After running this code, you’ll have:
[19, 21, 27, 16, 37, 34, 27, 32, 33, 10, 0, 0]
To compute a running total from your list, use Enum.scan/2
:
cumulative = Enum.scan(list, &+/2)
This function walks through your list and accumulates values as it goes:
19
19 + 21 = 40
40 + 27 = 67
- and so on.
The resulting list is:
[19, 40, 67, 83, 120, 154, 181, 213, 246, 256, 256, 256]
By combining simple functions from Elixir’s standard library:
- You can pad a list to a specific length using
List.duplicate/2
. - You can calculate a running total using
Enum.scan/2
.
These small, composable functions let you transform lists cleanly and expressively—one of the many strengths of functional programming in Elixir.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.