Is it possible to do the same with Lists, e.g. like that:
iex> [2] = [1, 2, 3]
# MatchError
I guess that the inherent nature of linked lists (which make it easy to pattern-match heads/tails) might complicate things. Also I got the fact that in this case it might not make sense to pattern-match for variable binding . But it might be useful to pattern-match in this case for conditions/tests.
One can simply use Enum.member? but I don’t see an easy way to avoid conditions like we do when using pattern-matching in general or in functions argument.
Yes I know about head/tail pattern-matching for Lists but I was curious to know if more elaborated options exists… Maybe with more advanced Elixir Data Structure besides Maps?
Just noticed the tag besides your username… I bought your book . A long time ago tbh… But it’s on the queue… I’m currently learning Elixir/Phoenix basics from other PragProg books I have…
As @benwilson512 said, you cannot pattern match in the middle of a list. If you are looking for a convenient and readable way to check for inclusion, you can do this though:
2 in [1, 2, 3]
You can also use it in guards:
case 2 do
x when x in [1, 2, 3] -> :yes
_ -> :no
end
Yeah I noticed it, and edited!
in fact you just gave me what I was looking for (namely guard clause) but I might stated the problem wider to learn a little more
Edit: I think that this bit is_integer(x) and might be an addition brought by an update later on…
Also it’s still interesting to know and behaves carefully with edge cases.
Important thing to notice in order to understand the behavior of in with ranges, is that a range is an Enumerable of integers. Therefore, (0..10) includes 5 but not 5.5, nor 5.0 (see the is_integer(x) in the guard expansion).
That is consistent with how Enum.member? works on ranges:
This is quite surprising but makes me feel really good about myself because I always assert on the type first and then on the range of acceptable values.
EDIT: Oops, I didn’t read all comments before commenting but the remark still stands.