I would like to use an is_range()
guard. For example:
def foo(bar) when is_range(bar) do
# stuff
end
But is_range
doesn't exist? I'm using Elixir 1.0.5
I tried
def foo(bar) when Range.range?(bar) do
# stuff
end
but this didn't work either.
What should I do?
The type of functions you can use in guards is quite limited.
http://elixir-lang.org/getting-started/case-cond-and-if.html
A range is a Struct which are maps, so you can use the is_map
function.
iex(1)> foo = 1..3
1..3
iex(2)> is_map(foo)
true
A Range is a map that looks like %{ __struct__: Range, first: 1, last: 3}
However, there is a better way to accomplish what you want by using pattern matching in function args rather than guards.
def fun(%Range{} = range) do
Map.from_struct(range)
end
This will match only a Range Struct, not any map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With