binarypaladin

binarypaladin

Using a compile time mutable registry?

Let me start by saying that while I have done some basic coding in Elixir and messed with Ecto and Phoenix I am coming from a mostly Ruby/class-based OOP background, and I can tell I have a lot brain-training to do. The main issue is dealing with immutable structures. It’s been smooth sailing thus far actually but… in a project I’m messing around with I’ve hit an issue.

Let’s say I have a struct/module named Thing. A Thing can be related to other things via some kind of value—let’s say I just have a key named relationships. The problem I see is when you have a struct of thing1 and thing2 that relate back and forth. If this was OOP and I was building a class or even a simpler structure like a hash, thing1 would get created first then you’d create thing2 and probably have it point back to thing1. From there you’d mutate thing1’s relationships to point to thing2. However, since I cannot mutate thing1, changing the relationships results in a new struct which points to thing2 which points to the old thing1.

At runtime it seems like you can accomplish this with a GenServer. All the Thing things understand that they need to talk to a GenServer and related a name. In this case, thing1 would have a reference to a name “thing2” that, at some point in the future, would resolve to the actual thing2 once defined.

What I really want is a global map available at runtime but generated dynamically at compile time. In terms of OOP, these structs are just “instances” of Thing. What would be better would be to have a module named ThingsRegistry with a function called get that took a string or atom and returned a named struct but, unlike a GenServer is not a process but rather the map that get is reading from has been set at compile time and perhaps register to replace the name map.

Can a macro take an existing function, get the return data, and then overwrite it?

I understand that I might be thinking about this all wrong and if that’s the issue, please feel free to let me know.

First Post!

mudasobwa

mudasobwa

Creator of Cure

I am not sure I understand the requirements properly, but this is the raw implementation of the module holding map built in the compile time

defmodule AllInOne.Thing do
  defstruct params: %{}
end

defmodule AllInOne.Registry do
  @things %{
    foo: %AllInOne.Thing{params: %{id: 1}},
    bar: %AllInOne.Thing{params: %{id: 2}}
  }

  @spec things :: map()
  def things, do: @things

  @spec thing(atom()) :: %AllInOne.Thing{} | nil
  def thing(name), do: Map.get(@things, name)
end

AllInOne.Registry.thing(:foo)
# ⇒ %AllInOne.Thing{params: %{id: 1}}

Here I built the map statically, but one might easily call another Elixir code there to build it dynamically. The only requirement, the called code should have been already compiled (it might be in the same project, but it cannot be in the same module, because modules get compiled “all-at-once”.)

Can a macro take an existing function, get the return data, and then overwrite it?

Sure it can. Here is an example from my Telemetría library, that grabs a function and wraps the call. You might want to explore this library source because it also modifies a code a lot during compile time.

Most Liked

mindok

mindok

As always, it depends what you’re trying to do…

If you are looking at maintaining relationships between Things, probably the easiest way to look at it is to separate the entities from their relationships (i.e. model it as a digraph with nodes and edges - you could take a look at GitHub - bitwalker/libgraph: A graph data structure library for Elixir projects · GitHub for inspiration).

Other than that, looking up other entities by some kind of key is a pretty common approach. How that is implemented depends on what you are trying to achieve (in detail). For example, GitHub - lau/tzdata: tzdata for Elixir. Born from the Calendar library. · GitHub provides a timezone database for elixir - it builds the data and relationships in ets on startup (and periodically updates on a schedule when timezone databases update) and provides data back to consumers via lookups on the ets tables. Incidentally, it is building links between entities as part of the database build process to allow alias names for timezones.

al2o3cr

al2o3cr

What you’re describing sounds a lot like ETS except for the compile-time stuff.

The stdlib uses ETS to store graphs (see :digraph and :digraph_utils) because it’s a mutable key-value store that can be shared with other processes.

For a simpler example, here’s an Advent of Code solution from the 2018 problems that uses an ETS table as a doubly-linked circular list:

https://github.com/al2o3cr/advent-of-code/blob/d35005bc722d304005d538f572a9ab345f24e08f/day9/part2.exs

Each element in the list has an identifying “value” and the values of its left and right neighbors; the list is traversed by repeatedly looking up entries by the first value and then recursively following the links.

For that problem, the structure was really convenient: each update was a fixed, small number of steps way from the previous update and inserted or removed a single element. That meant changing three entries in ETS, versus rewriting every following entry in a map or list.

Qqwy

Qqwy

TypeCheck Core Team

(emphasis mine)

I think we might have a case of the xy-problem here: You are looking for help with your supposed solution, but do not give us the full problem which makes it difficult to reason about the solution space. We’re slowly getting closer, as we now know that what you actually want to do has very little to do with ‘compile-time registries’.

You think you want to use bidirectional relationships between e.g. parents and children. However, what would you use these relationships for?
In object- and class-oriented languages where we deal a lot with inheritance, (bi-directional) relationships see a lot of use, especially since pass by (mutable) reference is very common, which is what gave rise to Joe Armstrong’s famous quote You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.

In an immutable functional language such as Elixir, we’d model the problem usually in a very different way where these mutable references are not needed. In these situations we often pick only one direction to go in (such as only parent → child) and that is how we fill in our structs. This is what e.g. Ecto’s relationships use.

But say we are indeed trying to model the ancestry of a family of humans, which is one of the few cases where indeed relationships in both directions might be important. For instance, we want to figure out who all the nieces and nephews of a particular family member are.
In that case, we use a dedicated graph datastructure. (which can be implemented under the hood in a number of ways on an immutable system, which I won’t go in here as it’s not important when using them). One example might be using libgraph but there are other libraries as well.

Last Post!

binarypaladin

binarypaladin

After sleeping on the issue I realized a couple things. Making the registry without metaprogramming was actually not complicated. The fact that it could be hand coded, even if awkwardly, made the clear enough. I just created a new Registry struct the keeps the map of the things as they are added and has a couple functions for associating things and it’s really, really simple—which is what I was going for.

I can carry on with no metaprogramming for now.

The only thing I needed to change was where some of the functions that focus on Thing, they need the whole registry in some cases—basically anything that needs to transverse relationships, which is a pretty small subset.

I think one of the things that @Qqwy hit on, even if not directly, with Joe Armstrong’s quote about the gorilla and his jungle wasn’t so much whether I want the banana but, in this case, I actually want the gorilla and his banana stash! If I want the gorilla (or the state he represents in what is becoming an increasingly absurd analogy) I need my functions to accept that state as opposed to looking for it implicitly—which is, obviously, one of the biggest gremlins in class-based OOP. (The gorilla cares about the bananas. The bananas do not care about the gorilla.)

Whether I ultimately store it in an ETS, a GenServer, or have some default hanging around in Mix.Config or FastGlobal is an implementation detail. In my tests, I can just create a Registry struct and make sure everything works.

Another added benefit of this approach is I can add other configuration/customization details to the registry that I was beginning to put into Mix.Config.

Also, with my goofy focus yesterday, I kept meeting Ecto. As it turns out there’s source code I can look at, lol. I start by saying “no metaprogramming” and then evolve to looking for a solution in that regard. Old habits die hard.

Thanks for your input everyone.

Where Next?

Popular in Questions Top

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
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44167 214
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

We're in Beta

About us Mission Statement