Rich_Morin

Rich_Morin

Formatting a list of strings - am I missing anything?

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

First 10 of 18 Posts Switch mode

blatyo

blatyo

Conduit Core Team

Should probably be:

def list_str( [ one ] ), do: to_string(one)

Otherwise, looks fine to me.

Rich_Morin

Rich_Morin OP

In case whatever is coming in isn’t already a string. Agreed, but is this any better than (say) “#{ one }”?

blatyo

blatyo

Conduit Core Team

They should be the same. I personally tend to use to_string instead of interpolation, when it’s only the value that I’m converting to a string. I’d use interpolation when I want to convert the values to a string and concatenate with something else.

Rich_Morin

Rich_Morin OP

That seems to be clearer, in terms of expressing intent, but in this case one could argue for staying in the same style as the following clauses. Dunno…

peerreynders

peerreynders

When it comes to serial commas the comma before the “and” is optional - it just can’t be there if you have less than three items.

So I guess recursion isn’t idiomatic?

  def list_str([]),
    do: ""

  def list_str([one]),
    do: to_string(one)

  def list_str(list),
    do: list_str(list, [])

  defp list_str([], [h, n | t]),
    do: list_to_str(t, to_string(n) <> " and " <> to_string(h))

  defp list_str([h | t], rest),
    do: list_str(t, [h | rest])

  defp list_to_str([], str),
    do: str

  defp list_to_str([h | t], str),
    do: list_to_str(t, to_string(h) <> ", " <> str)

Rich_Morin

Rich_Morin OP

Thank you for that tour de force, Peer. However, it doesn’t produce the requested result, so a picky client might complain and a picky test suite would certainly fail. Do you have a version that would pass?

As I’m sure you realize, omission of the Oxford comma can lead to ambiguity. To cite a well known example, “I’d like to thank my parents, God and Mother Teresa…” So, pedants like me don’t consider it to be optional. (Then again, I also use a lot of optional parentheses and spaces in my code…)

Leaving that issue aside, I wonder about the use of <>. Is this version

to_string(n) <> " and " <> to_string(h)

actually better for some reason (e.g., faster) than this version?

 "#{ n } and #{ h }"

Finally, although your recursive approach is most impressive, does it have any other benefits (aside from its stunning clarity and simplicity) that you can suggest? Inquiring gnomes need to mine…

peerreynders

peerreynders

Consistent version

  def list_str([]),
    do: ""

  def list_str([one]),
    do: to_string(one)

  def list_str(list),
    do: list_str(list, [])

  defp list_str([], [h, n]),
    do: list_to_str([], to_string(n) <> " and " <> to_string(h))

  defp list_str([], [h, n | t]),
    do: list_to_str(t, to_string(n) <> ", and " <> to_string(h))

  defp list_str([h | t], rest),
    do: list_str(t, [h | rest])

  defp list_to_str([], str),
    do: str

  defp list_to_str([h | t], str),
    do: list_to_str(t, to_string(h) <> ", " <> str)

Easy version

  def list_str([]),
    do: ""

  def list_str([one]),
    do: to_string(one)

  def list_str([one, two]),
    do: to_string(one) <> " and " <> to_string(two)

  def list_str(list),
    do: list_str(list, [])

  defp list_str([], [h, n | t]),
    do: list_to_str(t, to_string(n) <> ", and " <> to_string(h))

  defp list_str([h | t], rest),
    do: list_str(t, [h | rest])

  defp list_to_str([], str),
    do: str

  defp list_to_str([h | t], str),
    do: list_to_str(t, to_string(h) <> ", " <> str)

actually better for some reason (e.g., faster) than this version?

Haven’t looked at it too deeply - my gut-response is that it likely should be faster but that doesn’t preclude some smarty-pants compile time magic from proving me wrong and even if there is runtime overhead it could be minimal - though I wouldn’t count on it without verification.

Rich_Morin

Rich_Morin OP

EEx uses “some smarty-pants compile time magic” to turn Phoenix templates into sets of functions; this form of string interpolation doesn’t seem all that different to this newbie…

NobbZ

NobbZ

The second versions is syntactic sugar for the second.

LostKobrakai

LostKobrakai

There’s also cldr_lists, which can do that for you. Especially if you might need multiple languages I’d look into that.

Where Next?

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement