#TIL #elixirlang 이 편한 match?/2

iex> match?(%{a: _}, %{a: 1, b: 2})
true
iex> match?(%{c: _}, %{a: 1, b: 2})
false

match?/2 매크로는 패턴에 매칭(matching)하는지를 boolean으로 리턴한다.

iex> match?(%{a: c}, %{a: 1, b: 2})
warning: variable "c" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:17
true
iex> c
c
** (CompileError) iex:18: undefined function c/0

매크로 안에서 심볼에 값을 바인딩 되지 않는다. context를 공유하지 않는 macro hygiene이 적용된다.

iex> match?(%{a: x} when x > 2, %{a: 4, c: 2})
true
iex> match?(%{a: x} when x < 2, %{a: 4, c: 2})
false

안에서 쓸 수 없을 것 같은 가드 절(guard clause)도 사용할 수 있다.

그래서? 단독으로 사용할 때는 시큰둥해진다. 여기에 다른 함수를 끼얹는다면?

iex> list = [a: 1, b: 2, a: 3]
[a: 1, b: 2, a: 3]
iex> Enum.filter(list, &match?({:a, _}, &1))
[a: 1, a: 3]
iex> Enum.any?(list, &match?({_, 3}, &1))
true
iex> Enum.all?(list, &match?({_, 3}, &1))
false
iex> Enum.find(list, &match?({:a, x} when x > 2, &1))
{:a, 3}

Enum.filter/2, Enum.any?/2, Enum.all?/2, Enum.find/3술어(predicate)를 인자로 받는 모든 함수에 편하게 쓸 수 있다.

Feedback plz <3 @ohyecloudy, ohyecloudy@gmail.com

A Random Post