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: 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}")

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: 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.

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.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
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
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
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
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 30877 112
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New

We're in Beta

About us Mission Statement