Sebb

Sebb

String.split vs Enum.split_with

There seems to be no way to split an Enum like String.split does. Actually those functions have very different semantics.

String.split("123045067809", "0") #=> ["123", "45", "678", "9"]

function I’d like to have:

l =  [1,2,3,0,4,5,0,6,7,8,0,9]
Enum.split(l, &(&1 == 0)) #=>[[1, 2, 3], [4, 5], [6, 7, 8], [9]]

this is there, but not what I want:

Enum.split_with(l, &(&1 == 0)) #=> {[0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8, 9]}

close:

Enum.chunk_by(l, &(&1 == 0)) #=> [[1, 2, 3], [0], [4, 5], [0], [6, 7, 8], [0], '\t']

I think this is the first time, I miss a funciton in stdlib, that I expected to be there.

String.split(string, pattern, options \\ [])

Divides a string into parts based on a pattern. [split]

Enum.split_with(enumerable, fun)

Splits the enumerable in two lists according to the given function fun. [split_with]

Marked As Solved

dimitarvp

dimitarvp

You can just pipe the chunk_by result like this: |> Enum.reject(&1 == [0])?

Also Liked

adamu

adamu

Obligatory benchmarks.

Name                      ips        average  deviation         median         99th %
recursion              3.98 M      251.49 ns ±11214.50%         188 ns         456 ns
foldr                  2.99 M      334.99 ns ±12387.85%         223 ns         506 ns
reduce                 2.70 M      370.10 ns  ±9843.80%         258 ns         567 ns
chunk_while            1.40 M      712.55 ns  ±4515.89%         532 ns         968 ns
chunk_by_reject        0.86 M     1164.60 ns  ±2888.22%         896 ns        1427 ns

Comparison:
recursion              3.98 M
foldr                  2.99 M - 1.33x slower +83.50 ns
reduce                 2.70 M - 1.47x slower +118.61 ns
chunk_while            1.40 M - 2.83x slower +461.06 ns
chunk_by_reject        0.86 M - 4.63x slower +913.11 ns

Operating System: macOS
CPU Information: Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz
Number of Available Cores: 4
Available memory: 24 GB
Elixir 1.14.0
Erlang 25.0

Out of curiosity, I included this reduce version too:

Enum.reduce(list, {_group = [], _acc = []}, fn
  0, {[], acc} -> {[], acc}
  0, {group, acc} -> {[], [Enum.reverse(group) | acc]}
  el, {group, acc} -> {[el | group], acc}
end)
|> case do
  {[], acc} -> Enum.reverse(acc)
  {group, acc} -> Enum.reverse([Enum.reverse(group) | acc])
end
Eiji

Eiji

Here you go:

defmodule Example do
  def sample(list) when is_list(list) do
    # we start with one empty list
    List.foldr(list, [[]], fn
      # in case we got 0
      # we are adding new empty list at beginning of result
      0, acc -> [[] | acc]
      # otherwise we are appending element
      # as a head of first list in result
      element, [head | tail] -> [[element | head] | tail]
    end)
  end
end

[1, 2, 3, 0, 4, 5, 0, 6, 7, 8, 0, 9]
|> Example.sample()
|> IO.inspect(charlists: :as_lists)
# [[1, 2, 3], [4, 5], [6, 7, 8], [9]]

See List.foldr/3 documentation.

hst337

hst337

Actually, this is not that hard to write. Just

def split(list, splitter, acc \\ [])
def split([], _, []), do: []
def split([], _, acc), do: [:lists.reverse acc]
def split([splitter | tail], splitter, acc) do
  [:lists.reverse(acc) | split(tail, splitter, [])]
end
def split([item | tail], splitter, acc) do
  split(tail, splitter, [item | acc])
end

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
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 200809061...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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 31142 143
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement