I recently wrote some Elixir to format a list of strings (eg, author names) for output. I think it’s reasonably idiomatic, but I probably missed a few tricks. Suggestions, anyone?
-r
It should work like this…
iex(0)> list_str []
""
iex(1)> list_str [1]
1
iex(2)> list_str [1,2]
"1 and 2"
iex(3)> list_str [1,2,3]
"1, 2, and 3"
And now, the code… (ducks)
@doc """
Join a list of strings into a (mostly) comma-delimited string.
"""
def list_str( [] ), do: ""
def list_str( [ one ] ), do: one
def list_str( [ one, two ] ), do: "#{ one } and #{ two }"
def list_str(inp_list) do
[ last | base_list ] = Enum.reverse(inp_list)
base_str = base_list
|> Enum.reverse()
|> Enum.join(", ")
"#{ base_str }, and #{ last }"
end