vermaxik
List Comparison (how it works)
Hello Elixirforum,
Could you please explain how List Comparison works in Elixir?
Why such list of integers returns true
iex(15)> [3,10] > [3,3,3,3]
true
And the same example list of strings:
iex(16)> ["3","10"] > ["3", "3", "3", "3"]
false
I would expect in both examples false because of list size.
Thank you!
Marked As Solved
NobbZ
List comparison works by comparing element by element.
For each pair of equal elements, the comparison advances to the next. The first that is not equal decides. And 10 is greater than 3 while "10" is not greater than "3".
You can learn more in the docs:
Also Liked
LostKobrakai
Lists are compared element by element, disregarding the size (tuples are compared by size then elements). So it should come down to integers and binaries comparing differently.
iex(1)> "10" > "3"
false
iex(2)> 10 > 3
true
hauleth
As for reasoning for this behaviour - computing size of list is as expensive as traversing whole list, so comparing two lists first by length and then by elements would make whole operation more expensive.
Last Post!
arbaz_asif
The most efficient way to compare two lists on the basis of their sizes is by using Enum.count() function from Enum Module. It will work like this:
Enum.count([3,10]) > Enum.count([3,3,3,3])
false
Enum.count(["3","10"]) > Enum.count(["3", "3", "3", "3"])
false
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
- #api
- #forms
- #metaprogramming
- #security
- #hex










