Can we assign default values while pattern matching?

Let’s say I have a list of Structs and I want to pattern-match on it.

e.g.

[%MyStruct{key1: val}] = List.first [%MyStruct{key1: val1}, %MyStruct{key2: val2},...]

If it fails to pattern-match then instead of raising an error we want to set the value of val to nil.
Otherwise the value of val will be val1.

The right hand side value come from a variable which can be a list of structs like shown above or something else.
What’s a good way to set the value of val to nil if we can’t pattern-match it!

Currently I’m doing something like this:

      val =  if Enum.empty?(variable) do
                nil
             else
               %MyStruct.PresentationMaterials{key1: val} = List.first(variable)
               val
             end

What’s a better way to achieve the same thing?

1 Like

It’s a good practice to add extra functions and pattern match on them. If I’m understanding what you’re wanting, it should be something like this specifically for the field you’re trying to fetch:

def key_value(%MyStruct{key1: value}), do: value
def key_value(%MyStruct{} = _), do: :nil

And to grab the value from the first item from the list:

def first_key_value([]), do: :nil
def first_key_value([first_item|_]) do
  key_value(first_item)
end
3 Likes