Flattening a multi dimensional list

I’m trying to turn

saves =
[
  [[sport_id: 1, play: true], [sport_id: 1, watch: true]],
  [[sport_id: 2, play: true], nil],
  nil
]

into

saves =
[
  [sport_id: 1, play: true, watch: true],
  [sport_id: 2, play: true]
]

code:

defmodule Flatten do
  @doc """
  Flattens a list by recursively flattening the head and tail of the list
  """
  def flatten([head | tail]), do: flatten(head) ++ flatten(tail)
  def flatten([]), do: []
  def flatten(element), do: [element]
end

and then when I try to use it in a module

saves =
[
  [[sport_id: 1, play: true], [sport_id: 1, watch: true]],
  [[sport_id: 2, play: true], nil],
  nil
]

ssaves = Enum.map(saves, fn {v} ->
	Flatten.flatten(v)
end)

But I get this error

[error] GenServer #PID<0.23720.0> terminating
** (FunctionClauseError) no function clause matching in anonymous fn/1 in
1 Like

General note: surrounding code with ``` will make code blocks format cleanly.

The error is here:

saves = Enum.map(saves, fn {v} ->

The anonymous function written here is expecting a tuple with a single element. That is not what the elements of saves are, so you get FunctionClauseError.

1 Like