Can you map a pattern to a non-empty array in an elixir?

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

So, I am wondering if I can map a pattern to a non-empty array? As you can see below, an additional Search leads to a nested branch, and therefore I use the with operator and hope 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 
+5
source share
1 answer

You can use the template [_ | _] [_ | _] 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 
+8
source

Source: https://habr.com/ru/post/1265109/


All Articles