Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir : Pattern match a function if a map contains at least one integer key

I want to achieve something like the below (which obviously does not work)

def f1(%{key => _}) when is_integer(key) do :error end
def f1(%{}) do :ok end

I could match a map in the function head and check for an integer key inside the function body. Just wondering if there is a better approach. Any suggestions?

like image 298
rahul Avatar asked Mar 05 '26 19:03

rahul


1 Answers

Nope, this can't be done with pattern matching. Here's how I'd implement it using the method you described:

def f1(%{} = map) do
  if map |> Map.keys() |> Enum.any?(&is_integer/1), do: :error, else: :ok
end
like image 186
Dogbert Avatar answered Mar 08 '26 16:03

Dogbert