Skip to content

Commit c5e8dfb

Browse files
authored
expand Kernel.in/2 docs re range check efficiency (#11570)
Current docs treat membership tests on lists and ranges using `Kernel.in/2` with the same warning in the doc saying that comparison on large lists/ranges is inefficient. This is true for lists, but not for ranges. A more efficient check is done there which can run in constant time. Update docs to explain that. Have omitted going into detail on how membership checks for ranges with steps are done, as that seems less relevant, and the general comment that the check can be done efficiently still holds true.
1 parent c7e92e4 commit c5e8dfb

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

lib/elixir/lib/kernel.ex

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4175,8 +4175,10 @@ defmodule Kernel do
41754175
## Guards
41764176
41774177
The `in/2` operator (as well as `not in`) can be used in guard clauses as
4178-
long as the right-hand side is a range or a list. In such cases, Elixir will
4179-
expand the operator to a valid guard expression. For example:
4178+
long as the right-hand side is a range or a list.
4179+
4180+
If the right-hand side is a list, Elixir will expand the operator to a valid
4181+
guard expression which needs to check each value. For example:
41804182
41814183
when x in [1, 2, 3]
41824184
@@ -4188,6 +4190,15 @@ defmodule Kernel do
41884190
is best to stop using guards and use a more appropriate data structure, such
41894191
as `MapSet`.
41904192
4193+
If the right-hand side is a range, a more efficient comparison check will be
4194+
done. For example:
4195+
4196+
when x in 1..1000
4197+
4198+
translates roughly to:
4199+
4200+
when x >= 1 and x <= 1000
4201+
41914202
### AST considerations
41924203
41934204
`left not in right` is parsed by the compiler into the AST:

0 commit comments

Comments
 (0)