Rich_Morin

Rich_Morin

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

Showing Posts 1 to 10

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? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews