egeersoz

egeersoz

I’m looking for some help in implementing a “deep search” or “deep find” function.

I have a list of maps that represent people and their dependents. Each dependent can also have dependents, who in turn can have their own dependents, etc. ad infinitum. Example below:

[
%{"Name" => "Bobby Drake", "Age" => 50},
%{"Name" => "Jack Nicholson", "Age" => 25},
%{"Name" => "Peter Nelson", "Age" => 70, "Dependents" => [
    %{"Name" => "Amber Nauta", "Age" => 30},
    %{"Name" => "Joseph Nauta", "Age" => 26}
  ]
},
%{"Name" => "Craig Brown", "Age" => 66, "Dependents" => [
    %{"Name" => "Trevor Brown", "Age" => 33, "Dependents" => [
       %{"Name" => "Allison Brown", "Age" => 10}
     ]
  ]
}

]

Given a name, I need to scan this entire list and find that person’s age. There can theoretically be hundreds of items, and dozens of levels of nesting. However, we can assume that names are unique — meaning, there will only be a single match, and once that match is found, the search function can stop, return the result and exit. I mention that because performance is important.

Showing Posts 1 to 5

kip

kip

ex_cldr Core Team

Here’s one solution that leans on Enum.reduce_while/2 since it allows early exit from a reduction.

defmodule Name do
  @list_of_maps [
    %{"Name" => "Bobby Drake", "Age" => 50},
    %{"Name" => "Jack Nicholson", "Age" => 25},
    %{
      "Name" => "Peter Nelson",
      "Age" => 70,
      "Dependents" => [
        %{"Name" => "Amber Nauta", "Age" => 30},
        %{"Name" => "Joseph Nauta", "Age" => 26}
      ]
    },
    %{
      "Name" => "Craig Brown",
      "Age" => 66,
      "Dependents" => [
        %{
          "Name" => "Trevor Brown",
          "Age" => 33,
          "Dependents" => [
            %{"Name" => "Allison Brown", "Age" => 10}
          ]
        }
      ]
    }
  ]

  def deep_find(list_of_maps \\ @list_of_maps, name) do
    Enum.reduce_while(list_of_maps, {:halt, nil}, fn
      %{"Name" => ^name}, _acc -> {:halt, name}
      %{"Dependents" => dependents}, _acc ->
        case deep_find(dependents, name) do
          ^name -> {:halt, name}
          nil -> {:cont, nil}
        end
      _other, _acc -> {:cont, nil}
    end)
  end
end

iex> Name.deep_find "Allison Brown" 
"Allison Brown"
iex> Name.deep_find "Peter Nelson" 
"Peter Nelson"
iex> Name.deep_find "Pirate Pete" 
nil

Happy to answer questions any time.

Aetherus

Aetherus

Just a depth-first search:

defmodule DFS do
  def search([%{"Name" => name} = found | _], name) do
    found
  end

  def search([head | tail], name) do
    search(head["Dependents"], name) || search(tail, name)
  end

  def search(_nil_or_empty_list, _name) do
    nil
  end
end

Not tail-recursion, but as you said there are only dozens of levels of nesting, this should work fine.

egeersoz

egeersoz OP

Thanks, this is interesting! I don’t want to get the name though. I want to get the map itself so I can access its other properties, such as age. :grinning:

kip

kip

ex_cldr Core Team

No problem there, just a small change to either solution. For mine:

  def deep_find(list_of_maps \\ @list_of_maps, name) do
    Enum.reduce_while(list_of_maps, {:halt, nil}, fn
      %{"Name" => ^name} = found, _acc -> {:halt, found}
      %{"Dependents" => dependents}, _acc ->
        case deep_find(dependents, name) do
          %{"Name" => ^name} = found -> {:halt, found}
          nil -> {:cont, nil}
        end
      _other, _acc -> {:cont, nil}
    end)
  end

iex> Name.deep_find "Allison Brown"
%{"Age" => 10, "Name" => "Allison Brown"}
iex> Name.deep_find "Peter Nelson" 
%{
  "Age" => 70,
  "Dependents" => [
    %{"Age" => 30, "Name" => "Amber Nauta"},
    %{"Age" => 26, "Name" => "Joseph Nauta"}
  ],
  "Name" => "Peter Nelson"
}
iex> Name.deep_find "Pirate Pete"  
nil
mudasobwa

mudasobwa

Creator of Cure

While I would definitely go with Enum.reduce_while/3 suggested by @kip, I am to post two other approaches, sort of a top-up.

comprehension

level =
  fn input, f ->
    List.first(for(%{"Name" => "Allison Brown"} = map <- input, do: map)) ||
      for(%{"Dependents" => dependents} <- input, do: f.(dependents, f))
  end
level.(input, level) |> List.flatten() |> List.first()

Access

level = 
  fn input, f ->
    (input |> get_in([Access.filter(& &1["Name"] == "Allison Brown")]) |> List.first()) ||
      f.(get_in(input, [Access.all(), "Dependents"]) |> Enum.reject(&is_nil/1) |> List.flatten(), f)
  end
level.(input, level)
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews