Ettu_R
Accessing/updating Struct error during Enum.map
I have a struct define as follows
defmodule Employee do
defstruct [:fname, :lname, :id, salary: 0, job: "none"]
then I made a list, consisting of Employee structs and added one in there.
At some point I want to search the list for employee based on id number, this part also I’ve gotten to work.
But then I got a function promote, where I pick an employee based on id and then change job: field. This is where im running into problem. I want function return updated list of employees so i do Enum.map in the end and try to update job in there. Somethings wrong and Im not sure how to accomplish this?
in the following code
def promote(list) do
empId = IO.gets("Enter employee ID to promote: ")
empIdC = String.trim(empId)
getEmp = Enum.filter(list, fn x -> x.id == String.to_integer(empIdC) end) |> List.first()
IO.inspect(getEmp)
if getEmp != nil do
cond do
getEmp.job == "none" -> Enum.map(list, fn x -> if x.id == String.to_integer(empIdC) do x.job = "coder" end end)
end
end
end
When I inspect getEmp I see it has correct Struct inside
%Employee{fname: "m", id: 1, job: "none", lname: "a", salary: 0}
job is “none”, I want to promote it to “coder” and return new list
Error im getting with this code
** (CompileError) kt6.exs:71: cannot invoke remote function x.job/0 inside a match
(stdlib 3.8) lists.erl:1354: :lists.mapfoldl/3
(stdlib 3.8) lists.erl:1355: :lists.mapfoldl/3
(elixir 1.10.4) expanding macro: Kernel.if/2
Marked As Solved
LostKobrakai
This is not valid elixir. If you want to update the map use %{x | job: "coder"}. Also you should be aware that if without an else will return nil, so your function will return nil if no employee was found.
But more generally this is not really ideomatic in the big picture as well. If you select employees by id then it makes more sense to store them in a map with the employee id as a key, which makes selecting employees quite a bit simpler.
def promote(map) do
emp_id =
"Enter employee ID to promote: "
|> IO.gets()
|> String.trim()
|> String.to_integer()
if Map.has_key?(map, emp_id) do
Map.update!(map, emp_id, fn current -> %{current | job: "coder"} end)
else
map
end
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #podcasts
- #code-sync
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








