grangerelixx
Passing list values to a function
I have a list of maps.
For example,
students = [%{ sid: 1, name: "Bob", score: 80}, %{ sid: 2, name: "Kelly", score: 60},.....]
I have a function that accepts a single student map as a parameter,
calculate_percentage(student) do
something
end
I want to be able to pass each map in students list to calculate_percentage function. I tried Enum.map but that returns a list again. Can I know how to pass each value in a list one by one to the calculate_percentage function? Any suggestions are appreciated.
Thanks! ![]()
Most Liked
derek-zhou
I think you are confused about what is side-effect. A function converts inputs to outputs. If the function does only this and nothing else, it is called a pure function, or a function without side effect. A side effect is something you want to achieve in addition to the conversion: Writing databases, sending some data to the network, etc.
If you don’t want side effect and don’t care about the return value, then there is really no point calling the function.
The :ok is just a place holder for the return value. In Elixir there is no void function. You are welcomed to discard the meaningless return value.
derek-zhou
Last Post!
APB9785
In elixir, everything is “discarded” except the last line of the function. For example:
def my_func(param1, param2) do
Database.query(param1) # returns list of users [%User{} ...]
UserProfile.update!(param1, param2) # returns %UserProfile{} struct
1 + 1
end
The only thing my_func is going to return is 2. The first two function calls will still happen - leading to potential “side_effects” (like updating a row in the database), but they have no effect on the return value of my_func. Only the last line is returned. If you want to return the result of several function in combination, you use the pipeline operator:
def my_func(user_id, new_email) do
User.get_user!(user_id)
|> User.update!(new_email)
|> Map.get(:email)
end
This function will fetch a User from the db, pass that user along to the next function where it gets updated in the db, and finally get the email from out of our updated %User{} struct.
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
- #code-sync
- #javascript
- #podcasts
- #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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









