Basic < Operator working between integer and list

How does the < work? By accident, in my code, I compared an integer with a list, and it gave me a boolean value as response instead of error.

iex(1)> integer = 1
1
iex(2)> list = [1]
[1]
iex(3) integer < list
true

So how does the operator work here?

</2 and friends work by comparing “terms” as explained in the erlang manual:

http://erlang.org/doc/reference_manual/expressions.html#term-comparisons

3 Likes

It is also explained on the Elixir guides: https://elixir-lang.org/getting-started/basic-operators.html

For those who don’t want to open another site:

The reason we can compare different data types is pragmatism. Sorting algorithms don’t need to worry about different data types in order to sort. The overall sorting order is defined below:

number < atom < reference < function < port < pid < tuple < map < list < bitstring
3 Likes

PS.: just expressing my opinion on the matter, I think this is a really nice way to handle comparison between different data types. I mean, a lot better than what JS does, trying to discover what the user means by comparing different types. And that also allows some powerful stuff, like using any type as a key on maps and still be able to do a binary search on it, without any extra function needed :smiley:

3 Likes