saverio-kantox

saverio-kantox

In a project I’m working in, I have to create a boatload of different structs, each containing a list of different types of objects. Think XML with types. The values cannot be set directly on fields because order must be preserved, so there is no explicit type spec on the struct (it has one field that contains a kwlist with the children)

So we are implementing Access on them, to be able to get lenses on them, but I would like the user of these type to not have to know beforehand what type should be put in each child.

What would be the natural way to expose to the user a “blueprint” of the correct struct for a key?

Can some of the callbacks for Access expose an empty struct of the correct type instead of nil?

Is it reasonable for the user to expect that put_in and related functions do initialize intermediate objects when needed? (In the style of mkdir -p)

Thanks for your opinions and suggestions.

Showing Posts 1 to 5

dimitarvp

dimitarvp

Some examples will help a lot, want to post some?

saverio-kantox

saverio-kantox OP

Here is some (writing from memory with a phone keyboard):

defmodule A do
  defstruct values: []

  @element name: "a", type: A, min_occurs: 0
  @element name: "b", type: B, max_occurs: 5
  @element name: "c", type: C

  # implementations of Access and Enumerable

  def fetch(a, key) when is_atom(key) do
    case Keyword.get(a.values, key, :no) do
      :no -> :error
      found -> {:ok, found}
    end
  end

  # more implementations when key is {atom, index} to retrieve a child after the first
end

thing_a = %A{values: [
  b: %B{…},
  b: %B{…},
  c: %C{…},
]
# suppose :some is an element of C

put_in(thing_a, [:a, :c, :some], "value")

In my mind, the user shouldn’t know the specific type of C, the above code should produce (up to reordering, with is out of scope here)

%A{values: [
  a: %A{values: [c: %{values: [some: "value"]}]},
  b: %B{…},
  b: %B{…},
  c: %C{…},
]

You can observe that the top level A and the nested C are created automatically.

I think I can achieve this behaviour but I’m not sure whether it breaks some contract and whether there are better ways to allow the user to put values creating the intermediate steps as needed.

peerreynders

peerreynders

This involves using functions-as-keys in the path list that know what empty struct to supply when one is needed.

Access.keys/2 does this for Maps and structs. Use its implementation

https://github.com/elixir-lang/elixir/blob/v1.8.2/lib/elixir/lib/access.ex#L484-L497

as a blueprint for what you need to do in your particular case.

saverio-kantox

saverio-kantox OP

Very interesting, I haven’t thought about it. So the user instead of providing just the key path, would provide something like

put_in(thing_a, [
  MyAccess.key_or_create(:a),
  MyAccess.key_or_create(:c),
  …
], "value")

and the functions will be created based on some protocol that I need to define and implement?

Makes total sense, I did not feel 100% comfortable in returning non-nils on missing keys.

peerreynders

peerreynders

Example:

defmodule Nav do
  def a,
    do: key(:a, [])

  def c,
    do: key(:c, [])

  def some,
    do: key(:some, [])

  defp key(key, default) do
    fn
      :get, data, next ->
        next.(Keyword.get(data, key, default))

      :get_and_update, data, next ->
        value = Keyword.get(data, key, default)

      case next.(value) do
        {old, update} ->
          {old, Keyword.put(data, key, update)}

        :pop ->
          {value, Keyword.delete(data, key)}
      end
    end
  end
end

thing = []
path = [Nav.a(), Nav.c(), Nav.some()]
new_thing = put_in(thing, path, "value")
IO.puts("#{inspect(new_thing)}")

update = &{&1, "more " <> &1}
{old_value, more_thing} = get_and_update_in(new_thing, path, update)
IO.puts("#{inspect(old_value)} #{inspect(more_thing)}")

result = get_in(more_thing, path)
IO.puts("#{inspect(result)}")

{deleted_value, pop_thing} = pop_in(more_thing, path)
IO.puts("#{inspect(deleted_value)} #{inspect(pop_thing)}")
$ elixir nav.exs
[a: [c: [some: "value"]]]
"value" [a: [c: [some: "more value"]]]
"more value"
"more value" [a: [c: []]]
— 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
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
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
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
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

Other Trending Topics Top

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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews