Elixir way of pattern-matching against constants in function signature

jarmo
Thu, 21 Jul 2022 18:00:46 +0000
Questions / Help

How is Elixir way of pattern matching against other modules attribute value in function signatures?

For example, let’s imagine we have module like the following:

defmodule Bar do
  @const 42
  def const, do: @const
end

Pretty self-explanatory - there’s a module Bar with an attribute of @const and it is accessible from other modules via Bar.const().

I would like to use that value of 42 in other function signatures without writing it. How would I do that?

I’ve tried so far:

defmodule Foo do
  def quux(Bar.const), do: IO.println("hi const!")
  def quux(_), do: IO.println("hi var!")
end

Compilation fails:

cannot invoke remote function Bar.const/0 inside a match

Okay, only values/variables are supported so I tried to be clever and use ^ like this:

defmodule Foo do
  @x Bar.const
  def quux(^@x), do: IO.println("hi const!")
  def quux(_), do: IO.println("hi var!")
end

Compilation still fails:

invalid argument for unary operator ^, expected an existing variable, got: ^@x

What I’ve currently done so far to achieve my goal is something like the following:

defmodule Foo do
  def quux(val) do
    if val == Bar.const do
      IO.println("hi const!")
    else
      IO.println("hi var!")
    end
  end
end

However, I don’t feel that this is an Elixir way. How should I approach this kind of a problem?

7 posts - 7 participants