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:
https://hexdocs.pm/elixir/operators.html#comparison-operators
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.







