kouluelixir

kouluelixir

Initialising structs and incrementing value for each new struct

I am a beginner making a code with module. Employee module has a struct and a function. Employees have names, id’s, salaries and jobs. I have gotten updating jobs and salaries to work.

I still need for the employee id to update for each new employee. I also want to be able to assign a first and last name for each new employee. I tried to do that following this: Learn With Me: Elixir - Structs (#18) (‘Packaging Struct Data and Functions’). But for some reason, it didn’t work, even if I copied their code.

Is this possible? Thank you in advance.

defmodule Employee do

    defstruct firstName: "", lastName: "", id: 0, salary: 0, job: :none

    def new() do

        %Employee{}

    end

    def promote(employee) do

        case employee.job do

            :none -> employee = %{employee | job: :coder, salary: 2000}

            :coder -> employee = %{employee | job: :designer, salary: 4000}

            :designer -> employee = %{employee | job: :manager, salary: 6000}

            :manager -> employee = %{employee | job: :ceo, salary: 8000}

        end

    end

	def increment_id(employee) do
		%Employee{employee | id: employee.id + 1}
	end
end

employee = Employee.new("John", "Smith")
IO.puts("Employee name: #{employee.firstName} #{employee.lastName}. ID: #{employee.id}.
Job and salary: #{employee.job}, #{employee.salary}")


employee = Employee.promote(employee)
IO.puts("Employee name: #{employee.firstName} #{employee.lastName}. ID: #{employee.id}.
Job and salary: #{employee.job}, #{employee.salary}")

employee = Employee.promote(employee)
IO.puts("Employee name: #{employee.firstName} #{employee.lastName}. ID: #{employee.id}.
Job and salary: #{employee.job}, #{employee.salary}")

employee = Employee.demote(employee)
IO.puts("Employee name: #{employee.firstName} #{employee.lastName}. ID: #{employee.id}.
Job and salary: #{employee.job}, #{employee.salary}")


employee2 = Employee.new("Jane", "Doe")
IO.puts("Employee name: #{employee2.firstName} #{employee2.lastName}. ID: #{employee2.id}.
Job and salary: #{employee2.job}, #{employee2.salary}")

Marked As Solved

Matsa59

Matsa59

Hello, let’s explain step by step :wink:

employee = Employee.new("John", "Smith")

This line we call the function new/2 in a module called Employee. In your case this function doesn’t exist. You defined the function new/0 that doesn’t take any parameter.

So let’s update our code to have the right function:


defmodule Employee do
  defstruct first_name: "", last_name: "", id: 0, salary: 0, job: :none

  # Obviously you can call parameter without _var
  # I just add it to clarify the code in the function
  def new(first_name_var, last_name_var) do
    %Employee{first_name: first_name_var, last_name: last_name_var}
  end

  def promote(employee) do
    # ...
  end

  def increment_id(employee) do
    # ...
  end
end

in Elixir only modules names are in camel case, otherwise it’s in kebab case that’s why I changed firstName to first_name.

If you have any other question just ask :wink:

Have a great day

edit : Try to create a function display/1 that take an employee as parameter. Then simply call Employee.display(employee) to execute the IO.puts/1 :wink:
The main objectives of Modules is to reduce the code size meaning when you can factor something, create a function.

Also Liked

tomkonidas

tomkonidas

in Elixir only modules names are in camel case, otherwise it’s in kebab case that’s why I changed firstName to first_name .

It is actually snake_case and not kebab-case :wink:

dom

dom

There’s a nice tutorial on Agent: Agent - The Elixir programming language

More typically you’d just use a DB. If this is for testing or playing around, you can also use :erlang.unique_integer.

axelson

axelson

Scenic Core Team

I would like to note that for a production system you’d probably want to generate the incrementing ids in the database.

Matsa59

Matsa59

Yeah, you can use Agent or GenServer to hold the value.
Or simply use the previous employee’s id and increment it by one.

employee1 = Employee.new("John", "Doe")
employee2 = Employee.new("Jane", "Doe")

# So here employee1.id == 0 and employee2.id == 0
employee2 = %{employee2 | id: employee1.id + 1}

Often this will be enough

Or using an GenServer

defmodule MyGenServer do
  use GenServer

  def start_link(state) do
    GenServer.start_link(MyGenServer, state, name: :my_gen_server)
  end
  
  # Here state is the 2nd param of `GenServer.start_link/3`
  def init(state), do: {:ok, state}

  def incr do
    # Here we use the name of the GenServer
    GenServer.call(:my_gen_server, :incr)
  end

  # server side, access through GenServer.call or GenServer.cast

  def handle_call(:incr, _from, state) do
    {:reply, state, state + 1}
  end
end

# code to use the GenServer that will manage our id incr

MyGenServer.start_link(0) #  {:ok, pid} =>
# We dont really care of the pid here because we named our GenServer
# A named GenServer is accessible using its name instead of its PID
MyGenServer.inc() # 0
MyGenServer.inc() # 1
MyGenServer.inc() # 2
MyGenServer.inc() # 3

So update your Employee module to have

defmodule Employee do
  defstruct first_name: "", last_name: "", id: nil, salary: 0, job: :none

  # Obviously you can call parameter without _var
  # I just add it to clarify the code in the function
  def new(first_name_var, last_name_var) do
    %Employee{
      first_name: first_name_var, 
      last_name: last_name_var, 
      id: MyGenServer.inc()
    }
  end

You can read more about GenServer here

Matsa59

Matsa59

Yeah of course, I supposed he wants to do something that increment one by one :wink:

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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement