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
adamu

adamu

iex(2)> l |> Enum.join() |> String.split("0")
["123", "45", "678", "9"]

:troll:

Interesting though, especially as Enum.intersperse/2 exists.

LostKobrakai

LostKobrakai

Not much shorter, but using Enum instead of recursion:

l =  [1,2,3,0,4,5,0,6,7,8,0,9]

Enum.chunk_while(l, [], fn 
  0, acc -> {:cont, Enum.reverse(acc), []}
  element, acc -> {:cont, [element | acc]}
end, fn
  [] -> {:cont, []}
  acc -> {:cont, Enum.reverse(acc), []}
end)
# [[1, 2, 3], [4, 5], [6, 7, 8], [9]]

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
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

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement