YMMV as to where this falls on the golf-vs-readability spectrum, but it’s shorter:
def segment_path(s) do
s
|> String.split("/", trim: true)
|> Enum.scan({nil, ""}, fn el, {_, path} ->
{el, "#{path}/#{el}"}
end)
end
The tricky part here is that we only care about part of the “accumulator” for Enum.scan.
Alternatively, you could divide the work into clearer parts:
def segment_path(s) do
s
|> String.split("/", trim: true)
|> Enum.scan([""], &[&1 | &2])
|> Enum.map(&{hd(&1), Enum.join(Enum.reverse(&1), "/")})
end
The scan here builds a list of lists with (reversed) paths:
[["path"], ["to", "path"], ["segment", "to", "path"]]
Then the map converts those into the desired output shape.






















