silviurosu
Enum.sort does not work as expected
I have a situation that I can not figure out yet for some time and it drives me nuts. Either Enum.sort is not working as expected either I am doing it wrong.
I have some rules have a name and depend on each other. Source is the name of the dependency. I am trying to sort them ascending by dependency to be able to use them later to compute some amounts:
rules = [
%{
name: "ambassador1",
source: "ambassadors"
},
%{
name: "zuppler fee",
source: "total"
},
%{
name: "ambassadors",
source: "zuppler fee"
}
]
sorter = fn
sorter = fn
%{name: name1}, %{source: source2} when name1 == source2 -> true
%{source: source1}, %{name: name2} when source1 == name2 -> false
%{name: name1, source: source1}, %{name: name2, source: source2} when name1 == name2 and source1 == source2 -> true
%{name: name1, source: source1}, %{name: name2, source: source2} -> name1 < name2 and source1 < source2
end
_, _ -> false
end
rules |> Enum.sort(sorter) |> IO.inspect()
Result is:
[
%{name: "ambassadors", source: "zuppler fee"},
%{name: "zuppler fee", source: "total"},
%{name: "ambassador1", source: "ambassadors"}
]
when the expected result would be something like:
[
%{name: "zuppler fee", source: "total"},
%{name: "ambassadors", source: "zuppler fee"},
%{name: "ambassador1", source: "ambassadors"}
]
Can somebody give me a hint?
Marked As Solved
al2o3cr
Calling sorter with %{name: "zuppler fee", source: "total"} and %{name: "ambassador1", source: "ambassadors"} is going to return false, so I don’t think Enum.sort would find the configuration you’re looking for. The position of %{name: "ambassador1", source: "ambassadors"} in the result depends on the existence of %{name: "ambassadors", source: "zuppler fee"}…
Consider topological sort + tree traversal algorithms for this one.
Also Liked
LostKobrakai
Last Post!
ondrej-tucek
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









