Here’s another option!
def segment_path(path) when is_binary(path) do
segments = String.split(path, "/", trim: true)
paths =
Enum.reduce(segments, [], fn
segment, [] -> ["/#{segment}"]
segment, [head | _tail] = whole -> ["#{head}/#{segment}" | whole]
end)
Enum.zip(segments, Enum.reverse(paths))
end
end
What makes this more readable IMHO:
- Fewer LOC
- Contained in one function which tells me a clear story
- Building the paths as we move forward in a visually clear way with interpolation rather than
list |> Enum.reverse() |> Enum.join() - Only reversing one list at the end
- Using
Enum.reduce/3which is very familiar to most Elixir devs
You can of course pipe the reduce block into Enum.reverse() instead of inlining it in the zip call, if that’s your preference
As an added bonus this implementation benchmarks 20% faster on my machine than your original ![]()






















