How to quote a wildcard in a pattern matching?

Hi there !

I was wondering if it was possible to quote a wildcard in order to do a kind of maybe in pattern matching.

I tried to define the following macro :

  defmacro maybe(item) do
    quote do
      case unquote(item) do
        nil -> quote do: _
        _ -> unquote(item)

Then I was not able to use that in order to do pattern matching. I would like to do something like this :

    |> Stream.filter(fn
      ({%NaiveDateTime{year: maybe(year)}, month: maybe(month), ...}, _}) -> true
      (record) -> false

I am just wondering if I am taking the problem the right way. For now I wrap the code in functions with that pattern match each case, it makes a lot of duplication…

If anyone has any clue to do that right, I’m with !

Another way to see the problem could be to build the desired pattern and use it as pattern matching like :

pattern = %{year: 2015}
    |> Stream.filter(fn
      ({^pattern, _}) -> true
      (record) -> false

but it still do not work. But I feel to get closer to a cleaner solution

This is not how patterns work. When you bind the variable in pattern match then it will check for exact match, so:

map = %{a: 10, b: 20}
pattern = %{a: 10}

assert %{a: 10} = map
refute ^pattern = map
1 Like