kouluelixir

kouluelixir

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: https://inquisitivedeveloper.com/lwm-elixir-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}")

Showing Posts 1 to 8

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.

kouluelixir

kouluelixir OP

Thank you, I didn’t know about the camel/kebab case. How would you go about incrementing the id for each created employee? Is it even possible with Elixir?

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

dom

dom

There’s a nice tutorial on Agent: https://elixir-lang.org/getting-started/mix-otp/agent.html

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

Matsa59

Matsa59

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

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

Yes, but he didn’t talk about long term storage. And also the GenServer could also initialized its value for example (for hazardous old database lmao) :wink:

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:

— 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
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
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
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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 & Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews