> > This is true, but in Elixir a range is syntactic sugar specifically for a > compile-time list of integers. This is what lets it be used in guards and > pattern matching, where streams (and non-literal enumerables, and
comprehensions) cannot be employed. > So ranges are meant for bounded compile-time integer sequences, stream is > useful for building lazy infinite runtime ones, and the two have very > different intended usecases. :) The crux of what you are explaining boils down to the fact that until now, compile time, ranges have been afforded special treatment <https://elixirforum.com/t/can-i-check-if-value-is-in-range-in-a-guard-clause/14932/2> . If we really wanted to, we could make streams work in guard clauses as well. For instance, consider the infinite sequence of even numbers: ``` even_numbers = 0..∞//2 ``` That above sequence can be translated to a guard clause as: ``` defguard is_even(n) when rem(n, 2) == 0 ``` If we want this to work: ``` def eval(n) when n in 0..∞//2, do: true ``` then we only need to have a way of linking that `defguard` clause above with this infinite range. This most certainly will require some careful thought how you link them, but for now it may be plausible to expand the definition of the struct Range to encompass a module to delegate to where the infinite sequence is translated appropriately to an explicit guard clause. Just like currently the compiler is doing extra work to facilitate: ``` def eval(n) when n in [0, 2, 4, 6, 8, 10], do: true ``` likewise, there should be no fundamental objection to accommodate an infinite stream in a guard clause. This is what lets it be used in guards and pattern matching Which scenario can you pattern match a range? For instance in `iex` this fails: `[x | _] = 1..5`. Is there any compile time example you can share? So ranges are meant for bounded compile-time integer sequences This is not entirely true as you can compose a range dynamically: ``` def rnd(min, max), do: Enum.random(min..max) ``` -- You received this message because you are subscribed to the Google Groups "elixir-lang-core" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/CAAkfbUp6SWbUKa2n4%3Dsofg-WFG_UZu6rNn_jXo3VsdhTBpsGMQ%40mail.gmail.com.
