Is Enum.map inside another Enum.map possible?

Guys, I’m getting the following error when running this Enum.map, does anyone know why?
I can’t run an “Enum.map” inside another “Enum.map”?
How can I make this work?

Value reactions = [%{count: 1, name: "heavy_check_mark", users: ["1KDS232"]}]

Enum.map(json_atoms.messages, &%{ts: &1[:ts], 
            text: &1[:text], reactions: Enum.map(&1[:reactions], &%{reactions: &1[:name]})

Error:

== Compilation error in file lib/automation.ex ==
** (CompileError) lib/automation.ex:48: nested captures via & are not allowed: &(%{reactions: (&1)[:name]})
(stdlib 3.14) lists.erl:1358: :lists.mapfoldl/3
(stdlib 3.14) lists.erl:1359: :lists.mapfoldl/3
(elixir 1.11.2) src/elixir_fn.erl:134: :elixir_fn.escape/3
(stdlib 3.14) lists.erl:1358: :lists.mapfoldl/3
(elixir 1.11.2) src/elixir_fn.erl:134: :elixir_fn.escape/3
(elixir 1.11.2) src/elixir_fn.erl:138: :elixir_fn.escape/3
(stdlib 3.14) lists.erl:1358: :lists.mapfoldl/3
(elixir 1.11.2) expanding macro: Kernel.|>/2
** (exit) shutdown: 1
(mix 1.11.2) lib/mix/tasks/compile.all.ex:76: Mix.Tasks.Compile.All.compile/4
(mix 1.11.2) lib/mix/tasks/compile.all.ex:57: Mix.Tasks.Compile.All.with_logger_app/2
(mix 1.11.2) lib/mix/tasks/compile.all.ex:35: Mix.Tasks.Compile.All.run/1
(mix 1.11.2) lib/mix/task.ex:394: Mix.Task.run_task/3
(mix 1.11.2) lib/mix/tasks/compile.ex:119: Mix.Tasks.Compile.run/1
(mix 1.11.2) lib/mix/task.ex:394: Mix.Task.run_task/3
(iex 1.11.2) lib/iex/helpers.ex:104: IEx.Helpers.recompile/1

Yes You can, but You cannot use nested shortcuts :slight_smile:

So You need to replace one & &1 with the full function fn x -> x end.

3 Likes

Worse, I don’t understand Enum.map that much.
I’m doing some tests here, but to no avail.

Can you help me, how would it look?

If You look at your code, You are using 2 Enum.map with & &1 syntax, but You cannot use nested captures.

nested…

&%{reactions: &1[:name]}

main…

&%{ts: &1[:ts], text: &1[:text], reactions: Enum.map(&1[:reactions], &%{reactions: &1[:name]}

Just replace one with the full fn x → x end syntax, like this

Enum.map(json_atoms.messages, fn x -> %{ts: x[:ts], 
            text: x[:text], reactions: Enum.map(x[:reactions], &%{reactions: &1[:name]} end)

It has nothing to do with Enum.map, it’s how You write your anonymous functions, with or without shortcut.

3 Likes