galbangi
hi i am having problem with enum reduce. i am trying to sum values from lat of maps. getting error can any body help please
list = [
%{“price” => “100”, “trans_type” => “cr”},
%{“price” => “100”, “trans_type” => “db”},
%{“price” => “300”, “trans_type” => “cr”}
]
Enum.reduce(list, fn item, acc → %{val: String.to_integer(item[“price”]) + String.to_integer(acc[“price”])} end)
** (ArgumentError) errors were found at the given arguments:
1st argument: not a binary
:erlang.binary_to_integer(nil)
(stdlib 3.15.1) erl_eval.erl:685: :erl_eval.do_apply/6
(stdlib 3.15.1) erl_eval.erl:477: :erl_eval.expr/5
(stdlib 3.15.1) erl_eval.erl:791: :erl_eval.eval_map_fields/5
(stdlib 3.15.1) erl_eval.erl:260: :erl_eval.expr/5
(elixir 1.12.2) lib/enum.ex:2385: Enum.“-reduce/2-lists^foldl/2-0-”/3
thanks
Trending in Discussions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #ai
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #metaprogramming










Showing Posts 1 to 4- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
hudsonbay
Result: 500
APB9785
If the end result you want is an integer, then it’s best to start with an integer as the accumulator, like this:
mpope
Could do pure recursion:
qhwa
I just want to point out why you received that error.
The result of the
do_something(...)will be passed as the newacc. It is a map (%{val: 200}) after the first round of run.String.to_integer(%{val: 200}["price"]})leads to the exception. So you just need to change:valinto"price"as the map key to bypass the exception. But the above approaches provided by @hudsonbay @APB9785 and @mpope are better IMO.