dredison

dredison

How to recurse and build a key to access a child node

Hi,

So I’m new to Elixir and I’m struggling with a recursion question. I have a tree structure (of structs, with ordered lists of children), where each node has a single parent and many children. it can be nested to an arbitrary depth.

tree = %{
    id: "a",
    children: [
        %{ 
          id: "one",
          children: [
            %{ 
              id: "two"
            }
          ]
        },
        %{ 
          id: "three",
          children: [
            %{ 
              id: "four"
            },
            %{ 
              id: "five"
            },
          ]
        },
    ]
}

I’m trying to write a recursive function that will build an access key to a given node, identified by its ID.

Tree.path_to(tree, id, path \\ [])
``

So for example id "five", would return the following, which I can then use with the kernel's get_in and update_in functions.

[:children, Acess.to(1), :children, Access.to(1)]


I'm just too new to Elixir (and functional programming in general) to work it out so any help would be appreciated!

Marked As Solved

aziz

aziz

Hi dredison! Was going to give you a partial solution for your learning but I pretty much solved it:

# When parameters appear multiple times they are checked for equality.
def path_to(%{id: id}, id), do: []

def path_to(%{children: [_ | _] = children}, id) do
  case subpath_to(children, id) do
    {idx, path} -> [:children, idx | path]
    _ -> nil
  end
end

def path_to(_, _), do: nil

def subpath_to(children, id) do
  Enum.reduce_while(children, 0, fn child, idx ->
    path = path_to(child, id)
    if path, do: {:halt, {idx, path}}, else: {:cont, idx + 1}
  end)
end

You still have to do something to get the desired format. :slightly_smiling_face:

Tip: When writing recursive functions it always helps to handle the basic cases first and to make sure that there’s a terminating clause. Then you build on that and work your way down to the nested structures and see if you can use the functions that handle the basic cases.

Also Liked

dredison

dredison

Hey Aziz,

Amazing, thank you. Works like a charm. It’s also pointed me towards a better understanding of pattern matching and function arguments. Thanks again.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
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 52774 488
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

We're in Beta

About us Mission Statement