Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering/Pattern Matching in nested data structure

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?

like image 507
nohayeye Avatar asked Jan 30 '15 15:01

nohayeye


1 Answers

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).

like image 72
whatyouhide Avatar answered Sep 22 '22 10:09

whatyouhide