Enum.split_with/3

37 views
Skip to first unread message

virtual-light

unread,
Sep 8, 2022, 7:31:44 AM9/8/22
to elixir-lang-core
Proposal to expand Enum.split_with/2 with post-process function option similar to how it implemented in Enum.group_by/3 with third argument.

In my experience it is an often case when you need to split a enum through a function with a spec like:

@spec foo(term) :: {:ok, result_t} | {:error, error_t}

and receive two enums, where one contains successful results and another contains errors like: {list(result_t), list(error_t)}.

Enum.map/2 + Enum.split_by/2 seems to be a good choice for this work but unfortunately split_by it doesn't support post-process function (like third argument of Enum.group_by/3 does) so result of applying Enum.split_with/2 will be: {list({:ok, result_t}, list({:error, error_t})} instead.

I propose to expand Enum.split_with to this signature:
@spec split_with(t(), (element() -> as_boolean(term())), (element() -> any())) :: {list(), list()}
split_with(enumerable, split_fun, transform_fun \\ fn x -> x end)

so it can be used like this:

{successful_results, errors} =
  mu_enum
  |> Enum.map(&foo/1)
  |> Enum.split_by(& match?({:ok, _}, &1), fn {_, res} -> res end)
 
Because of lack of transform_fun in current implementation an additional step needed:
{Enum.map(successful_results, fn {_, res} -> res end), Enum.map(errors, fn {_, res} -> res end)}.

Manish sharma

unread,
Sep 8, 2022, 7:43:49 AM9/8/22
to elixir-l...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/3f87090e-b4ae-44d5-b81a-5cf645271440n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages