At7heb

At7heb

Integer.to_string_with_underscores?

I would like to have integers converted to strings with underscores. So instead of “77777777”, I would have “77_777_777”. Do I have to write my own?

(I’m writing a user program simulator for the SDS 940, a 24 bit machine with all documentation in octal.)

Marked As Solved

sabiwara

sabiwara

Elixir Core Team

Maybe this snippet taken from the Elixir formatter can help:

        digits
        |> String.to_charlist()
        |> Enum.reverse()
        |> Enum.chunk_every(3)
        |> Enum.intersperse(~c"_")
        |> List.flatten()
        |> Enum.reverse()
        |> List.to_string()

Also Liked

adamu

adamu

Here’s a version that does it by calculating the offset and building up the string in a single pass.

  def annotate(str) do
    length = byte_size(str)
    offset = rem(length, 3)
    {acc, rest} = String.split_at(str, offset)
    do_annotate(acc, rest)
  end

  defp do_annotate(acc, ""), do: acc
  defp do_annotate("", <<next::binary-3, rest::binary>>), do: do_annotate(next, rest)

  defp do_annotate(acc, <<next::binary-3, rest::binary>>),
    do: do_annotate(<<acc::binary, ",", next::binary>>, rest)

In my benchmarks it’s about 3x faster than the formatter implementation for 7-digit strings (8x for 1kb strings but that’s probably not a realistic use-case). A fun little challenge but I know people aren’t a fan of the bitstring syntax :slight_smile:

Name                ips        average  deviation         median         99th %
adamu            5.46 M      183.02 ns  ±8688.03%         125 ns         250 ns
formatter        1.97 M      508.32 ns  ±3909.15%         334 ns         542 ns

Comparison:
adamu            5.46 M
formatter        1.97 M - 2.78x slower +325.30 ns

Memory usage statistics:

Name         Memory usage
adamu             0.40 KB
formatter         1.89 KB - 4.75x memory usage +1.49 KB

Operating System: macOS
CPU Information: Apple M1 Pro
Number of Available Cores: 10
Available memory: 16 GB
Elixir 1.15.4
Erlang 26.1

Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 500 ms
reduction time: 0 ns
parallel: 1
inputs: none specified
Estimated total run time: 15 s
sabiwara

sabiwara

Elixir Core Team

Nice! I tried a spin-off based on binary comprehension out of curiosity, but it couldn’t beat recursion in the benchmarks (link) :slight_smile:

length = byte_size(str)
offset = rem(length - 1, 3) + 1
{acc, rest} = String.split_at(str, offset)
for <<group::binary-3 <- rest>>, into: acc, do: <<"_", group::binary-3>>

Results:

##### With input 7 digits #####
Name                    ips        average  deviation         median         99th %
Comprehension        3.95 M      253.43 ns ±12903.32%         167 ns         292 ns
Recursive            3.70 M      270.12 ns ±12392.13%         166 ns         292 ns

Comparison: 
Comprehension        3.95 M
Recursive            3.70 M - 1.07x slower +16.69 ns

Memory usage statistics:

Name             Memory usage
Comprehension           680 B
Recursive               488 B - 0.72x memory usage -192 B

##### With input 30 digits #####
Name                    ips        average  deviation         median         99th %
Recursive            3.00 M      333.77 ns  ±3331.98%         292 ns         458 ns
Comprehension        1.91 M      522.30 ns  ±3697.19%         459 ns         584 ns

Comparison: 
Recursive            3.00 M
Comprehension        1.91 M - 1.56x slower +188.53 ns

Memory usage statistics:

Name             Memory usage
Recursive             0.95 KB
Comprehension         1.95 KB - 2.06x memory usage +1 KB

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one ("skipping" all the other ones)? Would mix ecto.rollback -v 2008090...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31107 143
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement