Can I use case statement for Enum.filter function?

I have a case statement something like this

case Enum.filter(list, fn a → a.name == ^name end) do
a → a
_ → []
end

based on name it will give the list and if the name is not present it would give me an empty list. So I thought to use this behavior by case statement. But it’s giving me a warning

this clause cannot match because a previous clause at line 15 always matches

How can I match it against the empty list here?

This will always match, whatever a is. It is a rebind and is not equal to previous a.

it means this…

a = Enum.filter(list, fn a → a.name == ^name end)
1 Like

consider this

case 12345 do
  a -> 0
  12345 -> "ayyy"
end

a in this case matches everything, because it is an assignable variable. So this case will always return 0.
Why exactly?

a is not pinned, if you want to match on a then you have to pin the variable - however… you assigned a in a function inside Enum.filter - so the variable would not be available outside of the filter function anyways.

I think what you actually want is

Enum.find(list, & &1.name == name) || []
1 Like

Maybe || is not needed :slight_smile:

case something do
  [] -> "empty list"
  _ -> "anything else"
do
1 Like

wait I think we were all overthinking this… all you need is

Enum.filter(list, fn a → a.name == name end)
1 Like

Yeah actually I understood.

This really helped

also this

You can match

0 with [], 1 with [_], 1 or more with [_|_]

but it does not seem the case change the result, as mentioned by @Ninigi, it might not be needed :slight_smile:

1 Like