Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir is_range guard is not defined? What should I use?

Tags:

elixir

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?

like image 891
Josh Petitt Avatar asked Oct 18 '15 00:10

Josh Petitt


1 Answers

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.

like image 74
Fred the Magic Wonder Dog Avatar answered Oct 27 '22 16:10

Fred the Magic Wonder Dog