altuntasfatih

altuntasfatih

Is pattern matching posible in custom guard expressions?

Hey guys,
I have a question about custom guard expression.I am trying to write multiple guard expressions with pattern matching however it doesn’t work . not sure it is possible :slight_smile:
Briefly I wan to use guards like functions
this is a case which ı wan to write

defguard is_position({x,y}) when is_integer(x) and is_integer(y)
defguard is_position(_) when false

defp create_robot(_,  p) when not is_position(p) ,do: {:error, "invalid position"}

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hey @altunasfatih it is not possible to do pattern matching in guards. However you can achieve what you want by combining guards in this specific case:

defguard is_position(term) when tuple_size(term) == 2
  and is_integer(elem(term, 0))
  and is_integer(elem(term, 1))
jwarlander

jwarlander

Another way to do this would of course be to use structs..

defmodule Position do
  defstruct [:x, :y]

  def new(x, y) when is_integer(x) and is_integer(y) do
    %Position{x: x, y: y}
  end
end

defp create_robot(%Position{x: x, y: y}) do
  #... 
end

It’s a matter of preference, and how well it fits the use case of course. In this scenario you’re trusting those who work with the code to always use Position.new/2 to create the struct, if you want to be absolutely sure it always contains integers.

You could also refine the code so that the struct enforces the keys to be defined, and has a typespec; then you will get nice documentation of the expectations, and make it possible to check the constraints using Dialyzer:

defmodule Position do
  @enforce_keys [:x, :y]
  defstruct [:x, :y]
  @type t :: %__MODULE__{x: integer(), y: integer()}

  @spec new(integer(), integer()) :: Position.t()
  def new(x, y) when is_integer(x) and is_integer(y) do
    %Position{x: x, y: y}
  end
end

defp create_robot(%Position{x: x, y: y}) do
  #... 
end

Where Next?

Popular in Questions Top

New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement