1

I'm trying to create a user and add this new user to a list.

Every time a new user is created I want to add that new user to the existing list.

My code:

defmodule User do
  defstruct [:name, :city, company_code: 500]

  def create(params) do
    name = Keyword.get(params, :name)
    company_code = Keyword.get(params, :company_code)
    city = Keyword.get(params, :city)

    %Product{name: name, city: city, company_code: company_code}
  end

  def add_new_user(new_user, %User{}) do
    [:new_user | %User{}]
  end
end

How can I take the result I get when running def create and add it to a list every time a user is created using def create and display that list with all users?

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
gcm
  • 13
  • 3
  • Does this answer your question? [Add new element to list](https://stackoverflow.com/questions/35528875/add-new-element-to-list) – Samathingamajig Feb 17 '22 at 02:06

1 Answers1

2

Elixir can be challenging as a first language, but it does force you to think hard about how and where to pass values.

First off, your User struct seems like it was copy-pasted from a Product struct, so let's simplify the example:

defmodule User do
  defstruct [:first_name, :last_name]

  def create(params) do
    first_name = Keyword.get(params, :first_name)
    last_name = Keyword.get(params, :last_name)

    %User{first_name: first_name, last_name: last_name}
  end

  def add_user_to_list(new_user, list_of_existing_users \\ []) do
    [new_user | list_of_existing_users]
  end
end

Here, calling create/1, e.g. User.create(first_name: "Bob", last_name: "Smith") will return a User struct, e.g. %User{first_name: "Bob", last_name: "Smith"}.

If you want to add this to a list, you would pass the struct to the add_user_to_list/2 function:

[%User{first_name: "Bob", last_name: "Smith"}] = User.add_user_to_list(%User{first_name: "Bob", last_name: "Smith"})

The gotcha is that if you wanted to add additional users, you have to keep track of the UPDATED list variable and pass that BACK IN to the add_user_to_list/2 function. E.g.

user_list = []
u1 = User.create(first_name: "Bob", last_name: "Smith")
user_list = User.add_user_to_list(u1, user_list)
u2 = User.create(first_name: "Jane", last_name: "Doe")
user_list = User.add_user_to_list(u2, user_list)
# ... etc...
Everett
  • 8,746
  • 5
  • 35
  • 49