saverio-kantox

saverio-kantox

Access on structs with typed members

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.

Marked As Solved

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: []]]

Also Liked

saverio-kantox

saverio-kantox

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.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
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 27727 240
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement