Dusty

Dusty

Are nested structs an anti-pattern?

In the course of working on a tree-like data structure, I have designed a struct for each node in the tree. Since there are only 5 fields in each node, and all nodes have the same 5 fields, using a struct made sense to me.

However, one of the %Node{} struct fields contains the children of the node, which is a list of %Node{} structs, each of which can have its own children, and so on.

Given the challenges of accessing nested structs, I am beginning to question my original decision to use a struct instead of a map. I see that there are a number of posts already on how to access nested structs, but I’m still left asking: What does a struct really offer me here? Basically, it offers me the ability to limit the keys for each node. But is that a worthwhile tradeoff, given that the number of nested levels could be very high? Is it really a problem to just use a map?

The nature of the code is such that reaching down many levels at once is unlikely to be needed. For the most part, the tree will be walked one level at a time, but it will frequently be necessary to match on or modify fields in the node’s children (1 level down). It seems that the risk of unintended fields on the struct is perhaps not worth the complexity of using a struct in the first place.

Thoughts?

Most Liked

NobbZ

NobbZ

Not beeing able to use Access out of the box for your Node structs is actually a feature in my opinion. This enables you to come up with an implementation of Access that would make even more sense for a tree.

NobbZ

NobbZ

You can’t have circular references in immutable data structures.

You can of course simulate them using a flat datastructure and mentioning IDs.

dimitarvp

dimitarvp

You can draw inspiration from my extremely amateurish Trie library which was basically my first ever Elixir code somewhere back in 2016, here: https://github.com/dimitarvp/trie/blob/master/lib/trie.ex#L202. This demonstrates a basic Access.get implementation. Once your struct has that you could easily use get_in with instances of the struct as parameters.

Also check out Access docs. You need only implement a few functions to be able to use get_in and put_in.

domvas

domvas

Your struct is a good idea. It’s in fact better than a bare map because you need the field where children are stored. Without it, some of your code can break.
Regarding your node data / properties, you can have anything you want if you specify a filed for them like this:

@type t :: %Node{
  children: [Node.t], # This is mandatory for each node
  id: integer,        # This is an example data that must be defined for each node
  properties: map     # Other data specific to the node
}

Regarding the missing Enumerable, you have two solutions:

But on in all, it can be interesting to code your own traversal to have more control on what it’s done. Something like Node.update(depth, filter_fn, update_fn) could be nice for example.

Additionnally, if you want to go back and forth in your structure while updating it may be useful to investigate Zippers.
Hard to code but pure delight afterwards when using it.

NobbZ

NobbZ

I don’t see how accessing nested structs is different from nested maps, as structs are just maps with some additional field from this point of view.

Structs, nested or not, enable you to have at least limited compiletime checking of fieldnames.

Using bare maps you won’t have that.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
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 record...
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
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

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement