shmink
shmink

Reputation: 301

Pattern matching comparisons

I was creating a case statement and reached a case where I thought it might be nice/applicable to do a pattern matching comparison. I can't seem to find anything online about it. Take the following hypothetical example:

person = %Person{first_name: "Test", last_name: "example}
person2 = %Person{first_name: "another", last_name: "person"}

case list do
   [] -> 
     :empty

   [person, person2] == [%Person{} | _] ->
     :true

   [_] -> 
     :no_Person_struct
end

Granted, this would only check the head of the list but is there anything like this or a way to do it?

Also negation of it would be nice if possible. i.e.

[person, person2] == [%NotAPerson{} | _] == false -> :true

Syntax is very likely wrong.

EDIT: How about pattern matching in the arguments at least?

def([%Person{} | _] = people) do

Upvotes: 0

Views: 135

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

It can be done like this:

case list do
   [] -> :empty
   [%Person{} = _person | _] -> :first_is_a_person
   [_ | _] -> :first_is_not_a_person # because the previous clause did not match
end

To check all elements in a list, use Enum.all?/2:

Enum.all?(list, fn
  %Person{} -> true
  _ -> false
end)

Upvotes: 1

Related Questions