I am new to Elixir and still very confused with pattern matching.
[%{name: "Deutschland", code: "DE"}, %{name: "Frankreich", code: "FR"}]
def find_by_code([], _name), do: []
def find_by_code([h | t], query) do
if h[:code] == query do
IO.puts("MATCH")
IO.inspect(h)
else
IO.puts ("No match")
find_by_code(t, query)
end
end
Is that the best way to find the country by code?
You can pattern match as deep as you want:
def find_by_code([], _query),
do: nil # or whatever you want to mean "not found"
def find_by_code([%{code: query} = country|_t], query),
do: IO.inspect(country)
def find_by_code([_country|t], query),
do: find_by_code(t, query)
You can also use the Enum.find/3
with match?/2
, which may be more readable (as suggested in another answer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With