Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pattern match a non empty array in elixir?

Tags:

elixir

I have a User model with a has_many relationship to other_model. I have a function Search that searches the internet. What I would like to do is search the internet only if the has_many relationship is not an empty array.

So I'm wondering if I can pattern match against a non-empty array? As you can see below, the extra Search results in nested branch and hence I use the with statement and am hoping for a clean solution.

query = from a in Model, where: a.id == ^id, preload: [:some_associations]

with %{some_associations: some_associations} <- Repo.one(query),
      {:ok, some_results} <- Search.call(keywords, 1) do
            do_something_with(some_associations, some_results)
else
    nil -> IO.puts "query found nothing"
    {:error, reason} -> IO.puts "Search or query returned error with reason #{reason}"
end
like image 374
Terence Chow Avatar asked Mar 06 '17 19:03

Terence Chow


1 Answers

You can use the pattern [_ | _] to match non-empty lists:

{:ok, some_results = [_ | _]} <- Search.call(keywords, 1)
iex(1)> with xs = [_|_] <- [1, 2, 3] do {:ok, xs} else _ -> :error end
{:ok, [1, 2, 3]}
iex(2)> with xs = [_|_] <- [] do {:ok, xs} else _ -> :error end
:error
like image 74
Dogbert Avatar answered Nov 08 '22 06:11

Dogbert