V
V
Vyacheslav Kryukov2022-01-13 12:20:06
Modbus
Vyacheslav Kryukov, 2022-01-13 12:20:06

Why is there a mess with the entries in the structure of the Elixir module?

Based on TodoList from Sasha Yurich, I wrote a module with a Modbus configuration model (slave, reg_address, type) with variable name keys. Codes:

defmodule SlaveRegModel do
  defstruct vars: %{}

  def new(), do: %SlaveRegModel{}

  def add_setting(slave_reg_model, var_name, atr) do
    new_vars = Map.put(
        slave_reg_model.vars,
        var_name,
        atr
    )
    %SlaveRegModel{slave_reg_model | 
       vars: new_vars
    }
  end

  def setting?(slave_reg_model, var_name) do
    list = slave_reg_model.vars
    |> Stream.filter(fn {name, _} -> name == var_name end)
    |> Enum.map(fn {_, atr} -> atr end)
    hd(list)
  end

  def all(slave_reg_model) do
    slave_reg_model.vars
  end

  def delete_setting(slave_reg_model, var_name) do
    new_vars = Map.delete(slave_reg_model.vars, var_name)
    %SlaveRegModel{slave_reg_model | 
        vars: new_vars}
  end
end

The terminal shows that I create 3 variable entries, then I try to delete one, but in fact the entry was not deleted, and the modular structure was preserved.
61dfeca466996044888513.png
I tried the todo_crud.ex module code from Sasha Yurich's book "Elixir in action" - the same leapfrog when deleting and adding records. Not any idea.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Kryukov, 2022-01-14
@VAK_53

I found the answer:
when you delete the delete_setting command, you must save the value of the returned model= structure, i.e. "drive" the variable back and forth between the shell and the module.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question