I want to write a function that will, given a range and a value, n, check if the range spans exactly n..n. My first attempt looked something like this, but does not have the expected behavior (note the first return value is false)
defmodule Range do
def equal?(n, range) when range == n..n, do: true
def equal?(n, range), do: false
end
IO.puts(Range.equal?(1, 1..1)) # false
IO.puts(Range.equal?(1, 1..5)) # false
However, if I shift the approach to use pattern matching on the range argument, I can produce a function that works.
defmodule Range do
def equal?(n, n..n), do: true
def equal?(n, range), do: false
end
IO.puts(Range.equal?(1, 1..1)) # true
IO.puts(Range.equal?(1, 1..5)) # false
Looking at the two, it's not clear to me why they are not equivalent. If I replace the when range == n..n with when range == 1..1 this works as expected (obviously only for n = 1).
Why is this?